# -*- coding: utf-8 -*-

from configparser import ConfigParser
from flask import request, jsonify
from datetime import datetime
from uirls import web_socket
from tqdm import tqdm
import pymysql.cursors
import system_setup
import subprocess
import datetime
import requests
import pymysql
import hashlib
import logging
import asyncio
import pandas
import glob
import json
import time
import uuid
import copy
import cv2
import os

conf = ConfigParser()
conf.read("setting.ini", encoding='utf-8')

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


def mysql():
    mysql_connect = pymysql.connect(
        host=conf.get("mysql_settings", "host"),
        port=int(conf.get("mysql_settings", "port")),
        user=conf.get("mysql_settings", "user"),
        password=conf.get("mysql_settings", "password"),
        db="video_analysis",
        charset="utf8",
    )

    return mysql_connect


def mysql_kv():
    mysql_connect = pymysql.connect(
        host=conf.get("mysql_settings", "host"),
        port=int(conf.get("mysql_settings", "port")),
        user=conf.get("mysql_settings", "user"),
        password=conf.get("mysql_settings", "password"),
        db="video_analysis",
        charset="utf8",
        cursorclass=pymysql.cursors.DictCursor
    )

    return mysql_connect


def get_rtsp():
    jsons = request.json

    camera_ip = jsons["camera_ip"]
    camera_port = jsons["camera_port"]
    camera_account = jsons["camera_account"]
    camera_password = jsons["camera_password"]

    rtsp_addr = (
            "rtsp://"
            + f"{camera_account}"
            + ":"
            + f"{camera_password}"
            + "@"
            + f"{camera_ip}"
            + ":"
            + f"{camera_port}"
    )

    return rtsp_addr


def clean_rtsp_pic():
    file_list = glob.glob('/mnt/work/www/upload/images/*.jpg')
    # file_list = glob.glob('/usr/local/nginx/html/upload/cfs/*.jpg')

    if file_list is not None:
        for file_path in file_list:
            os.remove(file_path)


def task_classify(type_number):
    classify_dict = {
        "0": "object_recognition",
        "1": "object_detention",
        "2": "pose",
        "3": "overlap"
    }

    inference_mode = classify_dict[type_number]

    return inference_mode


def verify_integrity(filename, ori_md5):
    with open(filename, 'rb') as file:
        content = file.read()

    md5 = hashlib.md5()
    md5.update(content)
    file_md5 = md5.hexdigest()

    file.close()

    if file_md5 == ori_md5:
        logging.debug("文件完整性校验通过")

        return True

    else:
        logging.debug("文件完整性校验失败")

        return False


def get_db_args(docker_uuid, license_information):
    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_1 = ((f"SELECT "
                  f"device_number, "
                  f"channel_name, "
                  f"rtsp_addr, "
                  f"task_name, "
                  f"task_type, "
                  f"mark_position, "
                  f"model_path, "
                  f"model_name, "
                  f"model_type, "
                  f"detect_interval, "
                  f"detect_iou, "
                  f"detect_conf, "
                  f"alarm_type, "
                  f"alarm_interval, "
                  f"show_version, "
                  f"show_info_mark, "
                  f"show_roi_line, "
                  f"show_roi_label, "
                  f"show_fill_roi, "
                  f"show_fill_non_roi, "
                  f"show_result_box, "
                  f"show_result_label, "
                  f"show_result_conf, "
                  f"show_result_count, "
                  f"ip_addr "
                  f"FROM video_analysis_user.docker_args_{license_information} "
                  f"WHERE docker_uuid='%s';")
                 % docker_uuid)
        db_cursor.execute(sql_1)
        mydb.commit()
        args_0 = db_cursor.fetchone()
        args_1 = list(args_0)

        sql_2 = (f"SELECT detect_device_number FROM video_analysis_user.detect_device_number_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_2)
        mydb.commit()
        args_2 = db_cursor.fetchall()

        detect_device_number = []

        for ddn in args_2:
            ddn_str = ddn[0]
            detect_device_number.append(ddn_str)

        sql_3 = (f"SELECT alarm_object FROM video_analysis_user.alarm_object_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_3)
        mydb.commit()
        args_3 = db_cursor.fetchall()

        alarm_object = []

        for ao in args_3:
            ao_str = ao[0]
            alarm_object.append(ao_str)

        sql_4 = (f"SELECT roi_region_name, roi_region_id FROM video_analysis_user.roi_region_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_4)
        mydb.commit()
        args_4 = db_cursor.fetchall()

        set_roi_region = []

        for rr in args_4:
            roi_region_name = rr[0]
            roi_region_id = rr[1]

            sql_5 = (f"SELECT x, y FROM video_analysis_user.region_coordinate_{license_information} "
                     f"WHERE roi_region_id='%s';") % roi_region_id
            db_cursor.execute(sql_5)
            mydb.commit()
            args_5 = db_cursor.fetchall()

            region_coordinate = []

            for xy in args_5:
                x = str(int(eval(xy[0])))
                y = str(int(eval(xy[1])))
                new_coordinate = {"x": f"{x}", "y": f"{y}"}
                region_coordinate.append(new_coordinate)

            roi_region = {"set_roi_region_name": f"{roi_region_name}", "set_roi_region_coordinate": region_coordinate}
            set_roi_region.append(roi_region)

        sql_6 = "SELECT model_url FROM algorithm_shop WHERE model_name='%s';" % args_1[7]
        db_cursor.execute(sql_6)
        mydb.commit()
        args_6 = db_cursor.fetchone()

        if args_6[0] is None:
            sql_6 = "SELECT model_url FROM object WHERE model_name='%s';" % args_1[7]
            db_cursor.execute(sql_6)
            mydb.commit()
            args_6 = db_cursor.fetchone()

        for i in range(0, 25):
            if args_1[i] == "False":
                args_1[i] = ""

        jsons_rebuild = {
            "device_number": args_1[0],
            "channel_name": args_1[1],
            "ip_addr": args_1[24],
            "rtsp_addr": args_1[2],
            "task_name": args_1[3],
            "task_type": str(args_1[4]),
            "mark_position": args_1[5],
            "load_model_path": args_1[6],
            "load_model_name": args_1[7],
            "load_model_type": args_1[8],
            "load_model_url": args_6[0],
            "set_detect_device_number": detect_device_number,
            "set_detect_interval": args_1[9],
            "set_detect_iou": args_1[10],
            "set_detect_conf": args_1[11],
            "set_alarm_type": args_1[12],
            "set_alarm_object": alarm_object,
            "set_alarm_interval": args_1[13],
            "set_roi_region": set_roi_region,
            "set_show_version": bool(args_1[14]),
            "set_show_info_mark": bool(args_1[15]),
            "set_show_roi_line": bool(args_1[16]),
            "set_show_roi_label": bool(args_1[17]),
            "set_show_fill_roi": bool(args_1[18]),
            "set_show_fill_non_roi": bool(args_1[19]),
            "set_show_result_box": bool(args_1[20]),
            "set_show_result_label": bool(args_1[21]),
            "set_show_result_conf": bool(args_1[22]),
            "set_show_result_count": bool(args_1[23]),
            "docker_uuid": docker_uuid,
            "license_information": license_information
        }

        jsons_deliver = json.dumps(jsons_rebuild, ensure_ascii=False)

        return jsons_deliver

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()


def docker_operation_log(license_information, log_type, device_number, channel_name, log_action, task_name):
    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_create_log = (f"CREATE TABLE IF NOT EXISTS "
                          f"video_analysis_user.manage_args_{license_information} "
                          f"(id int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, "
                          f"log_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"log_time datetime, "
                          f"device_number varchar(30) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"channel_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"log_action varchar(50) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"task_name varchar(50) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL) "
                          f"ENGINE = InnoDB "
                          f"CHARACTER SET = utf8mb4 "
                          f"COLLATE = utf8mb4_general_ci "
                          f"ROW_FORMAT = Dynamic;")
        db_cursor.execute(sql_create_log)
        mydb.commit()

        sql_insert_log = ((f"INSERT INTO video_analysis_user.manage_args_{license_information} "
                           f"(log_type, log_time, device_number, channel_name, log_action, task_name) "
                           f"VALUES ('%s', NOW(), '%s', '%s', '%s', '%s');")
                          % (log_type, device_number, channel_name, log_action, task_name))
        db_cursor.execute(sql_insert_log)
        mydb.commit()

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()


def send_docker_operation_log():
    jsons = request.json

    license_information = jsons["license_information"]
    page = int(jsons["page"])
    limit = int(jsons["limit"])
    log_type = jsons["log_type"]
    channel_name = jsons["channel_name"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql_kv()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_create_log = (f"CREATE TABLE IF NOT EXISTS "
                          f"video_analysis_user.manage_args_{license_information} "
                          f"(id int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, "
                          f"log_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"log_time datetime, "
                          f"device_number varchar(30) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"channel_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"log_action varchar(50) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"task_name varchar(50) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL) "
                          f"ENGINE = InnoDB "
                          f"CHARACTER SET = utf8mb4 "
                          f"COLLATE = utf8mb4_general_ci "
                          f"ROW_FORMAT = Dynamic;")
        db_cursor.execute(sql_create_log)
        mydb.commit()

        if log_type != "":
            sql_part_log_type = f"AND log_type like '%{log_type}%' "

        else:
            sql_part_log_type = ""

        if channel_name != "":
            sql_part_channel_name = f"AND channel_name like '%{channel_name}%' "

        else:
            sql_part_channel_name = ""

        if page and limit is not None:

            sql = (f"SELECT log_type, DATE_FORMAT(log_time, '%Y-%m-%d %H:%i:%s') AS log_time, device_number, "
                   f"channel_name, log_action, task_name FROM video_analysis_user.manage_args_{license_information} "
                   f"WHERE 1=1 ") + sql_part_log_type + sql_part_channel_name + "ORDER BY log_time DESC;"
            db_cursor.execute(sql)
            cur_data = db_cursor.fetchall()

            items = []

            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['log_type'] = item['log_type']
                temp['log_time'] = item['log_time']
                temp['device_number'] = item['device_number']
                temp['channel_name'] = item['channel_name']
                temp['log_action'] = item['log_action']
                temp['task_name'] = item['task_name']
                items.append(temp)

            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = int(limit)

            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)

        else:
            return jsonify(
                code=1,
                msg="缺少必要参数page、limit"
            )

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


def create_docker_port(license_information):
    port_list = list(range(7000, 7100))
    port_iter = iter(port_list)

    docker_port = None

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql = f"SELECT docker_port FROM video_analysis_user.docker_args_{license_information};"
        db_cursor.execute(sql)
        mydb.commit()
        docker_used_port_tuple = db_cursor.fetchall()

        docker_used_port_list = []

        for docker_used_port_tuple_part in docker_used_port_tuple:
            docker_used_port_list.append(str(docker_used_port_tuple_part[0]))

        docker_check = True

        while docker_check:
            docker_port = next(port_iter)

            if str(docker_port) in docker_used_port_list:
                continue

            else:
                docker_check = False

        return docker_port

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()


def deliver_args(ip, port, suburl, jsons):
    ip = "http://127.0.0.1"
    url = f"{ip}:{port}/{suburl}"
    payload = jsons
    headers = {"content-type": "application/json"}

    response = requests.request(
        "POST",
        url,
        json=payload,
        headers=headers
    )

    return response


def get_base64img():
    jsons = request.json
    docker_uuid = jsons["uuid"]
    license_information = jsons["license_information"]
    ip_addr = jsons["ip_addr"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    json_output = {}

    rtsp_addr = get_rtsp()

    cap = cv2.VideoCapture(rtsp_addr)
    camera_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    camera_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    pic_time = str(time.strftime("%Y-%m-%d_%H-%M-%S",
                                 time.localtime(time.time())))

    temporary_pic_path = r'/mnt/work/www/upload/cfs/'
    # temporary_pic_path = r'/usr/local/nginx/html/upload/cfs/'
    temporary_pic_name = pic_time
    temporary_pic_format = ".jpg"
    temporary_pic_file = "{0}{1}{2}".format(temporary_pic_path,
                                            temporary_pic_name,
                                            temporary_pic_format)

    url_path = "/upload/cfs/"

    if docker_uuid == "":
        try:
            if cap.isOpened():
                ret, frame = cap.read()

                if ret:
                    cv2.imwrite(temporary_pic_file, frame)

            # temporary_pic = open(temporary_pic_file, "rb")
            # pic_base64 = str(base64.b64encode(temporary_pic.read()), 'utf-8')
            # temporary_pic.close()
            # os.remove(temporary_pic_file)

            pic_url = ip_addr + url_path + temporary_pic_name + temporary_pic_format

            # json_output['base64img'] = pic_base64
            json_output['base64img'] = pic_url
            json_output['camera_width'] = camera_width
            json_output['camera_height'] = camera_height

            return jsonify(
                msg="success",
                code=0,
                data=json_output
            )

        except Exception as e:
            print(e)

            return jsonify(
                msg="Server Internal Error",
                code=1
            )

        finally:
            cap.release()

    elif docker_uuid != "":
        try:
            if cap.isOpened():
                ret, frame = cap.read()

                if ret:
                    cv2.imwrite(temporary_pic_file, frame)

            # temporary_pic = open(temporary_pic_file, "rb")
            # pic_base64 = str(base64.b64encode(temporary_pic.read()), 'utf-8')
            # temporary_pic.close()
            # os.remove(temporary_pic_file)

            pic_url = ip_addr + url_path + temporary_pic_name + temporary_pic_format

            # json_output['base64img'] = pic_base64
            json_output['base64img'] = pic_url
            json_output['camera_width'] = camera_width
            json_output['camera_height'] = camera_height

            mydb = mysql()
            mydb.connect()
            db_cursor = mydb.cursor()

            try:
                sql = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                       f"SET base64img='%s', camera_width='%s', camera_height='%s' "
                       f"WHERE docker_uuid='%s';") % (pic_url, camera_width, camera_height, docker_uuid)
                db_cursor.execute(sql)
                mydb.commit()

            except Exception as e:
                print(e)

                return jsonify(
                    msg="Server Internal Error",
                    code=1
                )

            finally:
                db_cursor.close()
                mydb.close()

            return jsonify(
                msg="success",
                code=0,
                data=json_output
            )

        except Exception as e:
            print(e)

            return jsonify(
                msg="Server Internal Error",
                code=1
            )

        finally:
            cap.release()


def docker_create(docker_uuid, license_information):
    docker_image = "wisdiot_ai_1.0.1"
    docker_port = create_docker_port(license_information=license_information)

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql = (f"UPDATE video_analysis_user.docker_args_{license_information} SET docker_port='%s' "
               f"WHERE docker_uuid='%s';") % (docker_port, docker_uuid)
        db_cursor.execute(sql)
        mydb.commit()

        cmd = (
            # --network host --privileged
                f'nsenter -m -n -t 1 docker create -i -t -p {docker_port}:5000 '
                f'-v /mnt/work/www/upload/images:/mnt/wisdiot_ai/pic_temporary_save '
                f'-v /mnt/work/www/upload/model/:/mnt/wisdiot_ai/ai_models/ '
                f'--name "{docker_uuid}" '
                + docker_image
        )

        # cmd = (
        #     # --network host --privileged
        #         f'nsenter -m -n -t 1 docker create -i -t -p {docker_port}:5000 '
        #         f'-v /usr/local/nginx/html/upload/images/:/mnt/wisdiot_ai/pic_temporary_save/ '
        #         f'-v /usr/local/nginx/html/upload/model/:/mnt/wisdiot_ai/ai_models/ '
        #         f'--name "{docker_uuid}" '
        #         + docker_image
        # )
        subprocess.Popen(
            cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()


def docker_stop(docker_uuid, license_information):
    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql = (
                f"UPDATE video_analysis_user.docker_args_{license_information} "
                f"SET status='Inactive' "
                f"WHERE docker_uuid='%s';"
                % docker_uuid
        )
        db_cursor.execute(sql)
        mydb.commit()

        cmd = "nsenter -m -n -t 1 docker stop " + docker_uuid
        subprocess.Popen(
            cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def docker_start(docker_uuid, license_information):
    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_md5 = (f"SELECT md5, model_name FROM video_analysis_user.algorithm_{license_information} "
                   f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_md5)
        model_information_tuple = db_cursor.fetchone()
        md5 = model_information_tuple[0]
        model_name = model_information_tuple[1]

        sql_device = (f"SELECT device_number, channel_name, task_name "
                      f"FROM video_analysis_user.docker_args_{license_information} "
                      f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_device)
        device_information_tuple = db_cursor.fetchone()
        device_number = device_information_tuple[0]
        channel_name = device_information_tuple[1]
        task_name = device_information_tuple[2]

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    model_file_path = r"/mnt/work/www/upload/model/" + model_name
    # model_file_path = r"/usr/local/nginx/html/upload/model/" + model_name

    integrity = verify_integrity(filename=model_file_path, ori_md5=md5)

    if integrity:
        async def start_docker():
            mydb = mysql()
            mydb.connect()
            db_cursor = mydb.cursor()

            try:
                sql_docker_port = (f"SELECT docker_port FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_docker_port)
                mydb.commit()
                docker_port_tuple = db_cursor.fetchone()
                docker_port = str(docker_port_tuple[0])

                cmd_ufw = "nsenter -m -n -t 1 ufw allow " + docker_port
                subprocess.Popen(cmd_ufw, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                # cmd_firewall = ("nsenter -m -n -t 1 firewall-cmd --zone=public --add-port={}/tcp --permanent"
                #                 .format(docker_port))
                # subprocess.Popen(cmd_firewall, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                time.sleep(1)

                cmd = "nsenter -m -n -t 1 docker start " + docker_uuid
                subprocess.Popen(
                    cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                time.sleep(2)

            except Exception as e:
                print(e)

            finally:
                db_cursor.close()
                mydb.close()

        async def deliver():
            mydb = mysql()
            mydb.connect()
            db_cursor = mydb.cursor()

            try:
                time.sleep(4)

                sql = (
                        f"UPDATE video_analysis_user.docker_args_{license_information} SET status='Active' "
                        f"WHERE docker_uuid='%s';"
                        % docker_uuid
                )
                db_cursor.execute(sql)
                mydb.commit()

                sql_task_number = (f"SELECT task_type FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_task_number)
                mydb.commit()
                task_number_tuple = db_cursor.fetchone()
                task_number = str(task_number_tuple[0])

                sql_docker_port = (f"SELECT docker_port FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_docker_port)
                mydb.commit()
                docker_port_tuple = db_cursor.fetchone()
                docker_port = str(docker_port_tuple[0])

                sql_ip = (f"SELECT ip_addr FROM video_analysis_user.docker_args_{license_information} "
                          f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_ip)
                mydb.commit()
                ip_addr_tuple = db_cursor.fetchone()
                ip_addr = ip_addr_tuple[0]

                deliver_args(
                    jsons=get_db_args(docker_uuid=docker_uuid, license_information=license_information),
                    suburl=task_classify(type_number=task_number),
                    port=docker_port,
                    ip=ip_addr
                )

            except Exception as e:
                print(e)

                return jsonify(
                    msg="Server Internal Error",
                    code=1
                )

            finally:
                db_cursor.close()
                mydb.close()

            return jsonify(
                msg="success",
                code=0
            )

        asyncio.run(start_docker())
        asyncio.run(deliver())

        return jsonify(
            msg="success",
            code=0
        )

    else:
        docker_operation_log(license_information=license_information,
                             log_type="异常",
                             device_number=device_number,
                             channel_name=channel_name,
                             log_action=f"算法【{task_name}】未通过文件校验，任务启动失败。请前往插件商城重新下载该文件。",
                             task_name=task_name)

        return jsonify(
            code=1,
            msg="算法文件损坏，请重新下载"
        )


def delete_stop():
    jsons = request.json
    docker_uuid = jsons["uuid"]
    status = jsons["status"]
    license_information = jsons["license_information"]
    algorithm_id = jsons["algorithm_id"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        if status is not None:
            sql_log = (f"SELECT device_number, channel_name, task_name, docker_port "
                       f"FROM video_analysis_user.docker_args_{license_information} "
                       f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_log)
            log_tuple = db_cursor.fetchone()

            device_number = log_tuple[0]
            channel_name = log_tuple[1]
            task_name = log_tuple[2]
            docker_port = log_tuple[3]

            docker_operation_log(license_information=license_information,
                                 log_type="删除",
                                 device_number=device_number,
                                 channel_name=channel_name,
                                 log_action="终止并删除算法任务。",
                                 task_name=task_name)

            if status == "Active" or status == "Active_M":
                cmd_stop = "nsenter -m -n -t 1 docker kill " + docker_uuid
                subprocess.Popen(
                    cmd_stop, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                time.sleep(1)

                cmd_rm = "nsenter -m -n -t 1 docker rm " + docker_uuid
                subprocess.Popen(
                    cmd_rm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                cmd_close_port_ufw = "nsenter -m -n -t 1 ufw delete allow " + docker_port
                subprocess.Popen(
                    cmd_close_port_ufw, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                # cmd_close_port_firewall = ("nsenter -m -n -t 1 firewall-cmd --zone=public --remove-port={}/tcp "
                #                            "--permanent ".format(docker_port))
                # subprocess.Popen(
                #     cmd_close_port_firewall, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                # )

            elif status == "Inactive" or status == "Inactive_M":
                cmd_stop = "nsenter -m -n -t 1 docker kill " + docker_uuid
                subprocess.Popen(
                    cmd_stop, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                time.sleep(1)

                cmd_rm = "nsenter -m -n -t 1 docker rm " + docker_uuid
                subprocess.Popen(
                    cmd_rm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                cmd_close_port_ufw = "nsenter -m -n -t 1 ufw delete allow " + docker_port
                subprocess.Popen(
                    cmd_close_port_ufw, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                # cmd_close_port_firewall = ("nsenter -m -n -t 1 firewall-cmd --zone=public --remove-port={}/tcp "
                #                            "--permanent ".format(docker_port))
                # subprocess.Popen(
                #     cmd_close_port_firewall, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                # )

        elif status == "Null":
            pass

        sql_1 = (f"DELETE FROM video_analysis_user.docker_args_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_1)
        mydb.commit()

        sql_2 = (f"DELETE FROM video_analysis_user.detect_device_number_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_2)
        mydb.commit()

        sql_3 = (f"DELETE FROM video_analysis_user.alarm_object_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_3)
        mydb.commit()

        sql_4 = (f"DELETE FROM video_analysis_user.roi_region_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_4)
        mydb.commit()

        sql_5 = (f"DELETE FROM video_analysis_user.region_coordinate_{license_information} "
                 f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_5)
        mydb.commit()

        state_information = "active"
        sql_change_algorithm_state = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                      f"SET state_information='%s' "
                                      f"WHERE id='%s';") % (state_information, algorithm_id)
        db_cursor.execute(sql_change_algorithm_state)
        mydb.commit()

        sql_del_algorithm_docker_uuid = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                         f"SET docker_uuid='' "
                                         f"WHERE id='%s';") % algorithm_id
        db_cursor.execute(sql_del_algorithm_docker_uuid)
        mydb.commit()

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def docker_stop_manual():
    jsons = request.json
    docker_uuid = jsons["uuid"]
    license_information = jsons["license_information"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql = (
                f"UPDATE video_analysis_user.docker_args_{license_information} "
                f"SET status='Inactive_M' "
                f"WHERE docker_uuid='%s';"
                % docker_uuid
        )
        db_cursor.execute(sql)
        mydb.commit()

        cmd = "nsenter -m -n -t 1 docker kill " + docker_uuid
        subprocess.Popen(
            cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

        sql_log = (f"SELECT device_number, channel_name, task_name "
                   f"FROM video_analysis_user.docker_args_{license_information} "
                   f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_log)
        log_tuple = db_cursor.fetchone()

        device_number = log_tuple[0]
        channel_name = log_tuple[1]
        task_name = log_tuple[2]

        docker_operation_log(license_information=license_information,
                             log_type="停止",
                             device_number=device_number,
                             channel_name=channel_name,
                             log_action="手动停止任务。",
                             task_name=task_name)

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def docker_start_manual():
    jsons = request.json
    docker_uuid = jsons["uuid"]
    license_information = jsons["license_information"]
    if len(license_information) > 43:
        license_information = license_information[:43]
    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_md5 = (f"SELECT md5, model_name FROM video_analysis_user.algorithm_{license_information} "
                   f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_md5)
        model_information_tuple = db_cursor.fetchone()
        md5 = model_information_tuple[0]
        model_name = model_information_tuple[1]

        sql_device = (f"SELECT device_number, channel_name, task_name "
                      f"FROM video_analysis_user.docker_args_{license_information} "
                      f"WHERE docker_uuid='%s';") % docker_uuid
        db_cursor.execute(sql_device)
        device_information_tuple = db_cursor.fetchone()
        device_number = device_information_tuple[0]
        channel_name = device_information_tuple[1]
        task_name = device_information_tuple[2]

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()
    model_file_path = r"/mnt/work/www/upload/model/" + model_name
    # model_file_path = r"/usr/local/nginx/html/upload/model/" + model_name

    integrity = verify_integrity(filename=model_file_path, ori_md5=md5)

    if integrity:
        async def start_docker():
            mydb = mysql()
            mydb.connect()
            db_cursor = mydb.cursor()

            try:
                sql_docker_port = (f"SELECT docker_port FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_docker_port)
                mydb.commit()
                docker_port_tuple = db_cursor.fetchone()
                docker_port = str(docker_port_tuple[0])

                cmd_ufw = "nsenter -m -n -t 1 ufw allow " + docker_port
                subprocess.Popen(cmd_ufw, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                # cmd_firewall = ("nsenter -m -n -t 1 firewall-cmd --zone=public --add-port={}/tcp --permanent"
                #                 .format(docker_port))
                # subprocess.Popen(cmd_firewall, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                time.sleep(1)

                cmd = "nsenter -m -n -t 1 docker start " + docker_uuid
                subprocess.Popen(
                    cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )

                time.sleep(2)

                sql_log = (f"SELECT device_number, channel_name, task_name "
                           f"FROM video_analysis_user.docker_args_{license_information} "
                           f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_log)
                log_tuple = db_cursor.fetchone()

                device_number = log_tuple[0]
                channel_name = log_tuple[1]
                task_name = log_tuple[2]

                docker_operation_log(license_information=license_information,
                                     log_type="启动",
                                     device_number=device_number,
                                     channel_name=channel_name,
                                     log_action="手动启动任务。",
                                     task_name=task_name)

            except Exception as e:
                print(e)

                return jsonify(
                    msg="Server Internal Error",
                    code=1
                )

            finally:
                db_cursor.close()
                mydb.close()

            return jsonify(
                msg="success",
                code=0
            )

        async def deliver():
            mydb = mysql()
            mydb.connect()
            db_cursor = mydb.cursor()

            try:
                time.sleep(3)

                sql = (
                        f"UPDATE video_analysis_user.docker_args_{license_information} SET status='Active_M' "
                        f"WHERE docker_uuid='%s';"
                        % docker_uuid
                )
                db_cursor.execute(sql)
                mydb.commit()

                sql_task_number = (f"SELECT task_type FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_task_number)
                mydb.commit()
                task_number_tuple = db_cursor.fetchone()
                task_number = str(task_number_tuple[0])

                sql_docker_port = (f"SELECT docker_port FROM video_analysis_user.docker_args_{license_information} "
                                   f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_docker_port)
                mydb.commit()
                docker_port_tuple = db_cursor.fetchone()
                docker_port = str(docker_port_tuple[0])

                sql_ip = (f"SELECT ip_addr FROM video_analysis_user.docker_args_{license_information} "
                          f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_ip)
                mydb.commit()
                ip_addr_tuple = db_cursor.fetchone()
                ip_addr = ip_addr_tuple[0]

                deliver_args(
                    jsons=get_db_args(docker_uuid=docker_uuid, license_information=license_information),
                    suburl=task_classify(type_number=task_number),
                    port=docker_port,
                    ip=ip_addr
                )

            except Exception as e:
                print(e)

                return jsonify(
                    msg="Server Internal Error",
                    code=1
                )

            finally:
                db_cursor.close()
                mydb.close()

            return jsonify(
                msg="success",
                code=0
            )

        asyncio.run(start_docker())
        asyncio.run(deliver())

        return jsonify(
            msg="success",
            code=0
        )
    else:
        docker_operation_log(license_information=license_information,
                             log_type="异常",
                             device_number=device_number,
                             channel_name=channel_name,
                             log_action=f"算法【{task_name}】未通过文件校验，任务启动失败。请前往插件商城重新下载该文件。",
                             task_name=task_name)

        return jsonify(
            code=1,
            msg="算法文件损坏，请重新下载",
        )


def algorithm_list():
    jsons = request.json
    license_information = jsons["license_information"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information_check = copy.deepcopy(license_information)
    license_information = license_information.replace("-", "_")

    mydb = mysql_kv()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_check = (f"SELECT * FROM license_information_all WHERE license_information='%s';"
                     % license_information_check)
        db_cursor.execute(sql_check)
        mydb.commit()
        check_result = db_cursor.fetchone()

        if check_result is None:
            sql_create = (f"CREATE TABLE IF NOT EXISTS "
                          f"video_analysis_user.algorithm_{license_information} "
                          f"(id varchar(36) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"algorithm_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"task_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"model_path varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"model_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"model_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"alarm_object_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"ico varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"authorization_status varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"license_information varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"connection_status varchar(10) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"state_information varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"docker_uuid varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"object varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,"
                          f"version varchar(20) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"update_available varchar(10) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"md5 varchar(32) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"sequence_number int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY) "
                          f"ENGINE = InnoDB "
                          f"CHARACTER SET = utf8mb4 "
                          f"COLLATE = utf8mb4_general_ci "
                          f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create)
            mydb.commit()

            sql_copy = (f"INSERT INTO video_analysis_user.algorithm_{license_information} "
                        f"(id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, ico, "
                        f"authorization_status, license_information, connection_status, state_information, "
                        f"docker_uuid, object) "
                        f"SELECT id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, "
                        f"ico, authorization_status, license_information, connection_status, state_information, "
                        f"docker_uuid, object "
                        f"FROM video_analysis.algorithm;")
            db_cursor.execute(sql_copy)
            mydb.commit()

            sql_insert_information = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                      f"SET license_information='%s'") % license_information
            db_cursor.execute(sql_insert_information)
            mydb.commit()

            sql = (f"SELECT id AS algorithm_id, algorithm_name, COUNT(algorithm_name) AS algorithm_count, task_type, "
                   f"model_path, model_name, model_type, alarm_object_name, ico, connection_status, state_information, "
                   f"object "
                   f"FROM video_analysis_user.algorithm_{license_information} "
                   f"WHERE state_information='active' "
                   f"GROUP BY algorithm_name "
                   f"HAVING COUNT(algorithm_name) > 0 "
                   f"ORDER BY sequence_number;")
            db_cursor.execute(sql)
            mydb.commit()
            algorithms = db_cursor.fetchall()

        else:
            sql = (f"SELECT id AS algorithm_id, algorithm_name, COUNT(algorithm_name) AS algorithm_count, task_type, "
                   f"model_path, model_name, model_type, alarm_object_name, ico, connection_status, state_information, "
                   f"object "
                   f"FROM video_analysis_user.algorithm_{license_information} "
                   f"WHERE state_information='active' "
                   f"GROUP BY algorithm_name "
                   f"HAVING COUNT(algorithm_name) > 0 "
                   f"ORDER BY sequence_number;")
            db_cursor.execute(sql)
            mydb.commit()
            algorithms = db_cursor.fetchall()

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0,
        data=algorithms
    )


def object_list():
    jsons = request.json
    connection_status = jsons["connection_status"]

    if connection_status == "True":
        mydb = mysql_kv()
        mydb.connect()
        db_cursor = mydb.cursor()

        try:
            sql = ("SELECT id, object, model_path, model_name, model_type, alarm_object_name, ico "
                   "FROM object ORDER BY id ASC;")
            db_cursor.execute(sql)
            mydb.commit()
            objects = db_cursor.fetchall()

        except Exception as e:
            print(e)

            return jsonify(
                msg="Server Internal Error",
                code=1
            )

        finally:
            db_cursor.close()
            mydb.close()

        return jsonify(
            msg="success",
            code=0,
            data=objects
        )

    elif connection_status == "False":

        return jsonify(
            msg="success",
            code=0,
            data=[]
        )


def process_args():
    jsons = request.json
    json_check = copy.deepcopy(jsons)

    device_number = jsons["device_number"]
    channel_name = jsons["channel_name"]
    task_name = jsons["task_name"]
    mark_position = jsons["mark_position"]
    model_path = jsons["load_model_path"]
    model_name = jsons["load_model_name"]
    model_type = jsons["load_model_type"]
    user_set_detect_device_number = jsons["set_detect_device_number"]
    user_set_detect_interval = str(jsons["set_detect_interval"])
    user_set_detect_iou = str(jsons["set_detect_iou"])
    user_set_detect_conf = str(jsons["set_detect_conf"])
    user_set_alarm_type = jsons["set_alarm_type"]
    user_set_alarm_object = jsons["set_alarm_object"]
    user_set_alarm_interval = str(jsons["set_alarm_interval"])
    user_set_roi_region = jsons["set_roi_region"]
    user_set_show_version = bool(jsons["set_show_version"])
    user_set_show_info_mark = bool(jsons["set_show_info_mark"])
    user_set_show_roi_edge = bool(jsons["set_show_roi_line"])
    user_set_show_roi_label = bool(jsons["set_show_roi_label"])
    user_set_show_fill_roi = bool(jsons["set_show_fill_roi"])
    user_set_show_fill_non_roi = bool(jsons["set_show_fill_non_roi"])
    user_set_show_result_box = bool(jsons["set_show_result_box"])
    user_set_show_result_label = bool(jsons["set_show_result_label"])
    user_set_show_result_conf = bool(jsons["set_show_result_conf"])
    user_set_show_result_count = bool(jsons["set_show_result_count"])
    base64img = jsons["base64img"]
    docker_uuid = jsons["uuid"]
    status = jsons["status"]
    start_time = jsons["start_time"]
    stop_time = jsons["stop_time"]
    start_date = jsons["start_date"]
    stop_date = jsons["stop_date"]
    task_type = jsons["task_type"]
    docker_boot_mode = jsons["boot_mode"]
    camera_width = jsons["camera_width"]
    camera_height = jsons["camera_height"]
    operation = jsons["operation"]
    license_information = jsons["license_information"]
    connection_status = jsons["connection_status"]
    algorithm_id = jsons["algorithm_id"]
    ip_addr = jsons["ip_addr"]
    custom_name = jsons["custom_name"]

    rtsp_addr = get_rtsp()

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    del json_check["camera_ip"]
    del json_check["camera_port"]
    del json_check["camera_account"]
    del json_check["camera_password"]
    del json_check["operation"]
    del json_check["base64img"]
    del json_check["uuid"]
    del json_check["status"]
    del json_check["task_type"]
    del json_check["camera_width"]
    del json_check["camera_height"]
    del json_check["license_information"]
    del json_check["connection_status"]
    del json_check["algorithm_id"]
    del json_check["custom_name"]
    # del json_check["ip_addr"]

    json_check["rtsp_addr"] = rtsp_addr

    # dict_check = json.loads(json_check)

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        if docker_uuid == "":
            if docker_boot_mode == "auto":
                status = "Inactive"
            elif docker_boot_mode == "manual":
                status = "Inactive_M"

            docker_uuid = str(uuid.uuid4())

            sql_create_docker_args = (f"CREATE TABLE IF NOT EXISTS "
                                      f"video_analysis_user.docker_args_{license_information} "
                                      f"(docker_uuid varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                                      f"status varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"device_number varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"channel_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"rtsp_addr varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_name varchar(50) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"mark_position varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_path varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_device_number varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_iou varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_object varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"roi_region json NULL, "
                                      f"show_version varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_info_mark varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_line varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_non_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_box varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_count varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"base64img text "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, "
                                      f"boot_mode varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"docker_port varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"camera_width int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"camera_height int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"operation varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"ip_addr varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"normal_update_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"custom_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"sequence_number int(11)"
                                      f"NOT NULL AUTO_INCREMENT PRIMARY KEY)"
                                      f"ENGINE = InnoDB "
                                      f"CHARACTER SET = utf8mb4 "
                                      f"COLLATE = utf8mb4_general_ci "
                                      f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_docker_args)
            mydb.commit()

            sql_create_detect_device_number = (f"CREATE TABLE IF NOT EXISTS "
                                               f"video_analysis_user.detect_device_number_{license_information} "
                                               f"(id int(11) "
                                               f"NOT NULL AUTO_INCREMENT, "
                                               f"docker_uuid varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"detect_device_number varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"PRIMARY KEY (id) USING BTREE) "
                                               f"ENGINE = InnoDB "
                                               f"AUTO_INCREMENT = 95 "
                                               f"CHARACTER SET = utf8mb4 "
                                               f"COLLATE = utf8mb4_general_ci "
                                               f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_detect_device_number)
            mydb.commit()

            sql_create_alarm_object = (f"CREATE TABLE IF NOT EXISTS "
                                       f"video_analysis_user.alarm_object_{license_information} "
                                       f"(id int(11) "
                                       f"NOT NULL AUTO_INCREMENT, "
                                       f"docker_uuid varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"alarm_object varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"PRIMARY KEY (id) USING BTREE) "
                                       f"ENGINE = InnoDB "
                                       f"AUTO_INCREMENT = 67 "
                                       f"CHARACTER SET = utf8mb4 "
                                       f"COLLATE = utf8mb4_general_ci "
                                       f"ROW_FORMAT = Dynamic;")

            db_cursor.execute(sql_create_alarm_object)
            mydb.commit()

            sql_create_roi_region = (f"CREATE TABLE IF NOT EXISTS video_analysis_user.roi_region_{license_information} "
                                     f"(id int(11) "
                                     f"NOT NULL AUTO_INCREMENT, "
                                     f"docker_uuid varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_id varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_name varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"PRIMARY KEY (id) USING BTREE) "
                                     f"ENGINE = InnoDB "
                                     f"AUTO_INCREMENT = 111 "
                                     f"CHARACTER SET = utf8mb4 "
                                     f"COLLATE = utf8mb4_general_ci "
                                     f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_roi_region)
            mydb.commit()

            sql_create_region_coordinate = (f"CREATE TABLE IF NOT EXISTS "
                                            f"video_analysis_user.region_coordinate_{license_information} "
                                            f"(id int(11) NOT NULL AUTO_INCREMENT, "
                                            f"docker_uuid varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"roi_region_id varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"x varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"y varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"PRIMARY KEY (id) USING BTREE) "
                                            f"ENGINE = InnoDB "
                                            f"AUTO_INCREMENT = 432 "
                                            f"CHARACTER SET = utf8mb4 "
                                            f"COLLATE = utf8mb4_general_ci "
                                            f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_region_coordinate)
            mydb.commit()

            sql_1 = (
                        f"INSERT INTO video_analysis_user.docker_args_{license_information} "
                        f"(docker_uuid, status, start_time, stop_time, start_date, stop_date, "
                        f"device_number, channel_name, rtsp_addr, task_name, task_type, mark_position, model_path, "
                        f"model_name, model_type, detect_interval, detect_iou, detect_conf, alarm_type, "
                        f"alarm_interval, show_version, show_info_mark, show_roi_line, show_roi_label, show_fill_roi, "
                        f"show_fill_non_roi, show_result_box, show_result_label, show_result_conf, show_result_count, "
                        f"base64img, boot_mode, camera_width, camera_height, operation, ip_addr, custom_name) "
                        f"VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',"
                        f"'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',"
                        f"'%s', '%s');"
                    ) % (
                        docker_uuid,
                        status,
                        start_time,
                        stop_time,
                        start_date,
                        stop_date,
                        device_number,
                        channel_name,
                        rtsp_addr,
                        task_name,
                        task_type,
                        mark_position,
                        model_path,
                        model_name,
                        model_type,
                        user_set_detect_interval,
                        user_set_detect_iou,
                        user_set_detect_conf,
                        user_set_alarm_type,
                        user_set_alarm_interval,
                        user_set_show_version,
                        user_set_show_info_mark,
                        user_set_show_roi_edge,
                        user_set_show_roi_label,
                        user_set_show_fill_roi,
                        user_set_show_fill_non_roi,
                        user_set_show_result_box,
                        user_set_show_result_label,
                        user_set_show_result_conf,
                        user_set_show_result_count,
                        base64img,
                        docker_boot_mode,
                        camera_width,
                        camera_height,
                        operation,
                        ip_addr,
                        custom_name
                    )
            db_cursor.execute(sql_1)
            mydb.commit()

            for ddn in user_set_detect_device_number:
                sql_2 = (f"INSERT INTO video_analysis_user.detect_device_number_{license_information} "
                         f"(docker_uuid, detect_device_number) "
                         f"VALUES ('%s','%s');") % (docker_uuid, ddn)
                db_cursor.execute(sql_2)
                mydb.commit()

            for ao in user_set_alarm_object:
                sql_3 = (f"INSERT INTO video_analysis_user.alarm_object_{license_information} "
                         f"(docker_uuid, alarm_object) "
                         f"VALUES ('%s','%s');") % (docker_uuid, ao)
                db_cursor.execute(sql_3)
                mydb.commit()

            for rr_dict in user_set_roi_region:
                roi_region_name = rr_dict["set_roi_region_name"]
                roi_region_coordinate_list = rr_dict["set_roi_region_coordinate"]
                roi_region_id = uuid.uuid4()
                sql_4 = ((f"INSERT INTO video_analysis_user.roi_region_{license_information} "
                          f"(roi_region_id, docker_uuid, roi_region_name) "
                          f"VALUES ('%s','%s','%s');")
                         % (roi_region_id, docker_uuid, roi_region_name))
                db_cursor.execute(sql_4)
                mydb.commit()

                for roi_region_coordinate_dict in roi_region_coordinate_list:
                    coordinate_x = roi_region_coordinate_dict["x"]
                    coordinate_y = roi_region_coordinate_dict["y"]
                    sql_5 = ((f"INSERT INTO video_analysis_user.region_coordinate_{license_information} "
                              f"(roi_region_id, x, y, docker_uuid) "
                              f"VALUES ('%s','%s','%s','%s');")
                             % (roi_region_id, coordinate_x, coordinate_y, docker_uuid))
                    db_cursor.execute(sql_5)
                    mydb.commit()

            if connection_status == "False":
                state_information = "inactive"
                sql_change_algorithm_state = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                              f"SET state_information='%s' "
                                              f"WHERE id='%s';") % (state_information, algorithm_id)
                db_cursor.execute(sql_change_algorithm_state)
                mydb.commit()

                sql_change_algorithm_docker_uuid = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                                    f"SET docker_uuid='%s' "
                                                    f"WHERE id='%s';") % (docker_uuid, algorithm_id)
                db_cursor.execute(sql_change_algorithm_docker_uuid)
                mydb.commit()

            docker_create(docker_uuid=docker_uuid, license_information=license_information)

            docker_operation_log(license_information=license_information,
                                 log_type="新增",
                                 device_number=device_number,
                                 channel_name=channel_name,
                                 log_action="创建算法检测任务。",
                                 task_name=task_name)

        else:
            if status == "Null":
                if docker_boot_mode == "auto":
                    status = "Inactive"

                elif docker_boot_mode == "manual":
                    status = "Inactive_M"

                sql_1 = (
                        f"UPDATE video_analysis_user.docker_args_{license_information} "
                        f"SET status ='%s', start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                        f"device_number='%s', channel_name='%s', rtsp_addr='%s', task_name='%s', task_type='%s', "
                        f"mark_position='%s', model_path='%s', model_name='%s', model_type='%s', detect_interval='%s', "
                        f"detect_iou='%s', detect_conf='%s', alarm_type='%s', alarm_interval='%s', show_version='%s', "
                        f"show_info_mark='%s', show_roi_line='%s', show_roi_label='%s', show_fill_roi='%s', "
                        f"show_fill_non_roi='%s', show_result_box='%s', show_result_label='%s', show_result_conf='%s', "
                        f"show_result_count='%s', base64img='%s', boot_mode='%s', camera_width='%s', "
                        f"camera_height='%s', operation='%s', ip_addr='%s', custom_name='%s' "
                        f"WHERE docker_uuid='%s';"
                        % (
                            status,
                            start_time,
                            stop_time,
                            start_date,
                            stop_date,
                            device_number,
                            channel_name,
                            rtsp_addr,
                            task_name,
                            task_type,
                            mark_position,
                            model_path,
                            model_name,
                            model_type,
                            user_set_detect_interval,
                            user_set_detect_iou,
                            user_set_detect_conf,
                            user_set_alarm_type,
                            user_set_alarm_interval,
                            user_set_show_version,
                            user_set_show_info_mark,
                            user_set_show_roi_edge,
                            user_set_show_roi_label,
                            user_set_show_fill_roi,
                            user_set_show_fill_non_roi,
                            user_set_show_result_box,
                            user_set_show_result_label,
                            user_set_show_result_conf,
                            user_set_show_result_count,
                            base64img,
                            docker_boot_mode,
                            camera_width,
                            camera_height,
                            operation,
                            ip_addr,
                            custom_name,
                            docker_uuid
                        )
                )
                db_cursor.execute(sql_1)
                mydb.commit()

                sql_2 = (f"DELETE FROM video_analysis_user.detect_device_number_{license_information} "
                         f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_2)
                mydb.commit()

                for ddn in user_set_detect_device_number:
                    sql_3 = (f"INSERT INTO video_analysis_user.detect_device_number_{license_information} "
                             f"(docker_uuid, detect_device_number) "
                             f"VALUES ('%s','%s');") % (docker_uuid, ddn)
                    db_cursor.execute(sql_3)
                    mydb.commit()

                sql_4 = (f"DELETE FROM video_analysis_user.alarm_object_{license_information} "
                         f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_4)
                mydb.commit()

                for ao in user_set_alarm_object:
                    sql_5 = (f"INSERT INTO video_analysis_user.alarm_object_{license_information} "
                             f"(docker_uuid, alarm_object) "
                             f"VALUES ('%s','%s');" % (docker_uuid, ao))
                    db_cursor.execute(sql_5)
                    mydb.commit()

                sql_6 = (f"DELETE FROM video_analysis_user.roi_region_{license_information} "
                         f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_6)
                mydb.commit()

                sql_8 = (f"DELETE FROM video_analysis_user.region_coordinate_{license_information} "
                         f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_8)
                mydb.commit()

                for rr_dict in user_set_roi_region:
                    roi_region_name = rr_dict["set_roi_region_name"]
                    roi_region_coordinate_list = rr_dict["set_roi_region_coordinate"]

                    roi_region_id = uuid.uuid4()

                    sql_7 = (f"INSERT INTO video_analysis_user.roi_region_{license_information} "
                             f"(roi_region_id, docker_uuid, roi_region_name) "
                             f"VALUES ('%s','%s','%s');") % (roi_region_id, docker_uuid, roi_region_name)
                    db_cursor.execute(sql_7)
                    mydb.commit()

                    for roi_region_coordinate_dict in roi_region_coordinate_list:
                        coordinate_x = roi_region_coordinate_dict["x"]
                        coordinate_y = roi_region_coordinate_dict["y"]

                        sql_9 = ((f"INSERT INTO video_analysis_user.region_coordinate_{license_information} "
                                  f"(roi_region_id, x, y, docker_uuid) "
                                  f"VALUES ('%s','%s','%s','%s');")
                                 % (roi_region_id, coordinate_x, coordinate_y, docker_uuid))
                        db_cursor.execute(sql_9)
                        mydb.commit()

                docker_create(docker_uuid=docker_uuid, license_information=license_information)

                docker_operation_log(license_information=license_information,
                                     log_type="新增",
                                     device_number=device_number,
                                     channel_name=channel_name,
                                     log_action="创建算法检测任务。",
                                     task_name=task_name)

            else:
                rebuild_docker = False

                sql_update_custom_name = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                          f"SET custom_name='%s' "
                                          f"WHERE docker_uuid='%s';") % (custom_name, docker_uuid)
                db_cursor.execute(sql_update_custom_name)
                mydb.commit()

                sql_check_time = (f"SELECT start_time, stop_time, start_date, stop_date, boot_mode "
                                  f"FROM video_analysis_user.docker_args_{license_information} "
                                  f"WHERE docker_uuid='%s';") % docker_uuid
                db_cursor.execute(sql_check_time)
                mydb.commit()
                check_time = db_cursor.fetchone()

                check_start_time = check_time[0]
                check_stop_time = check_time[1]
                check_start_date = check_time[2]
                check_stop_date = check_time[3]
                check_docker_boot_mode = check_time[4]

                if check_docker_boot_mode == json_check["boot_mode"]:
                    if check_start_time == json_check["start_time"]:
                        if check_stop_time == json_check["stop_time"]:
                            if check_stop_date == json_check["stop_date"]:
                                if check_start_date == json_check["start_date"]:
                                    pass
                                else:
                                    sql_time = ((f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                 f"SET start_time='%s', stop_time='%s', start_date='%s', "
                                                 f"stop_date='%s', boot_mode='%s' WHERE docker_uuid='%s';")
                                                % (start_time,
                                                   stop_time,
                                                   start_date,
                                                   stop_date,
                                                   docker_boot_mode,
                                                   docker_uuid
                                                   ))
                                    db_cursor.execute(sql_time)
                                    mydb.commit()
                            else:
                                sql_time = ((f"UPDATE video_analysis_user.docker_args_{license_information} "
                                             f"SET start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                                             f"boot_mode='%s' WHERE docker_uuid='%s';")
                                            % (start_time,
                                               stop_time,
                                               start_date,
                                               stop_date,
                                               docker_boot_mode,
                                               docker_uuid
                                               ))
                                db_cursor.execute(sql_time)
                                mydb.commit()
                        else:
                            sql_time = ((f"UPDATE video_analysis_user.docker_args_{license_information} "
                                         f"SET start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                                         f"boot_mode='%s' WHERE docker_uuid='%s';")
                                        % (start_time,
                                           stop_time,
                                           start_date,
                                           stop_date,
                                           docker_boot_mode,
                                           docker_uuid
                                           ))
                            db_cursor.execute(sql_time)
                            mydb.commit()
                    else:
                        sql_time = ((f"UPDATE video_analysis_user.docker_args_{license_information} "
                                     f"SET start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                                     f"boot_mode='%s' WHERE docker_uuid='%s';")
                                    % (start_time,
                                       stop_time,
                                       start_date,
                                       stop_date,
                                       docker_boot_mode,
                                       docker_uuid
                                       ))
                        db_cursor.execute(sql_time)
                        mydb.commit()
                else:
                    change_status = None
                    if docker_boot_mode == "auto":
                        if status == "Active_M":
                            change_status = "Active"
                        elif status == "Inactive_M":
                            change_status = "Inactive"
                    elif docker_boot_mode == "manual":
                        if status == "Active":
                            change_status = "Active_M"
                        elif status == "Inactive":
                            change_status = "Inactive_M"

                    sql_time = ((f"UPDATE video_analysis_user.docker_args_{license_information} "
                                 f"SET status='%s', start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                                 f"boot_mode='%s' WHERE docker_uuid='%s';")
                                % (change_status,
                                   start_time,
                                   stop_time,
                                   start_date,
                                   stop_date,
                                   docker_boot_mode,
                                   docker_uuid
                                   ))
                    db_cursor.execute(sql_time)
                    mydb.commit()

                dict_value_list = []

                for value_ori in json_check.values():
                    dict_value_list.append(value_ori)

                database_args = get_db_args(docker_uuid=docker_uuid, license_information=license_information)
                data_check_get = database_args
                data_check = json.loads(data_check_get)

                del data_check["task_type"]
                del data_check["load_model_url"]

                for data_check_value in data_check.values():
                    if data_check_value in dict_value_list:
                        continue
                    else:
                        rebuild_docker = True
                        break

                if rebuild_docker:
                    status_check = copy.deepcopy(status)

                    if docker_boot_mode == "auto":
                        status = "Inactive"
                    elif docker_boot_mode == "manual":
                        status = "Inactive_M"

                    sql_1 = (
                            f"UPDATE video_analysis_user.docker_args_{license_information} "
                            f"SET status ='%s', start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', "
                            f"device_number='%s', channel_name='%s', rtsp_addr='%s', task_name='%s', task_type='%s', "
                            f"mark_position='%s', model_path='%s', model_name='%s', model_type='%s', "
                            f"detect_interval='%s', detect_iou='%s', detect_conf='%s', alarm_type='%s', "
                            f"alarm_interval='%s', show_version='%s', show_info_mark='%s', show_roi_line='%s', "
                            f"show_roi_label='%s', show_fill_roi='%s', show_fill_non_roi='%s', show_result_box='%s', "
                            f"show_result_label='%s', show_result_conf='%s', show_result_count='%s', base64img='%s', "
                            f"boot_mode='%s', camera_width='%s', camera_height='%s', operation='%s', ip_addr='%s', "
                            f"custom_name='%s' WHERE docker_uuid='%s';"
                            % (
                                status,
                                start_time,
                                stop_time,
                                start_date,
                                stop_date,
                                device_number,
                                channel_name,
                                rtsp_addr,
                                task_name,
                                task_type,
                                mark_position,
                                model_path,
                                model_name,
                                model_type,
                                user_set_detect_interval,
                                user_set_detect_iou,
                                user_set_detect_conf,
                                user_set_alarm_type,
                                user_set_alarm_interval,
                                user_set_show_version,
                                user_set_show_info_mark,
                                user_set_show_roi_edge,
                                user_set_show_roi_label,
                                user_set_show_fill_roi,
                                user_set_show_fill_non_roi,
                                user_set_show_result_box,
                                user_set_show_result_label,
                                user_set_show_result_conf,
                                user_set_show_result_count,
                                base64img,
                                docker_boot_mode,
                                camera_width,
                                camera_height,
                                operation,
                                ip_addr,
                                custom_name,
                                docker_uuid
                            )
                    )
                    db_cursor.execute(sql_1)
                    mydb.commit()

                    sql_2 = (f"DELETE FROM video_analysis_user.detect_device_number_{license_information} "
                             f"WHERE docker_uuid='%s';") % docker_uuid
                    db_cursor.execute(sql_2)
                    mydb.commit()

                    for ddn in user_set_detect_device_number:
                        sql_3 = (f"INSERT INTO video_analysis_user.detect_device_number_{license_information} "
                                 f"(docker_uuid, detect_device_number) "
                                 f"VALUES ('%s','%s');") % (docker_uuid, ddn)
                        db_cursor.execute(sql_3)
                        mydb.commit()

                    sql_4 = (f"DELETE FROM video_analysis_user.alarm_object_{license_information} "
                             f"WHERE docker_uuid='%s';") % docker_uuid
                    db_cursor.execute(sql_4)
                    mydb.commit()

                    for ao in user_set_alarm_object:

                        sql_5 = (f"INSERT INTO video_analysis_user.alarm_object_{license_information} "
                                 f"(docker_uuid, alarm_object) "
                                 f"VALUES ('%s','%s');" % (docker_uuid, ao))
                        db_cursor.execute(sql_5)
                        mydb.commit()

                    sql_6 = (f"DELETE FROM video_analysis_user.roi_region_{license_information} "
                             f"WHERE docker_uuid='%s';") % docker_uuid
                    db_cursor.execute(sql_6)
                    mydb.commit()

                    sql_8 = (f"DELETE FROM video_analysis_user.region_coordinate_{license_information} "
                             f"WHERE docker_uuid='%s';") % docker_uuid
                    db_cursor.execute(sql_8)
                    mydb.commit()

                    for rr_dict in user_set_roi_region:
                        roi_region_name = rr_dict["set_roi_region_name"]
                        roi_region_coordinate_list = rr_dict["set_roi_region_coordinate"]

                        roi_region_id = uuid.uuid4()

                        sql_7 = (f"INSERT INTO video_analysis_user.roi_region_{license_information} "
                                 f"(roi_region_id, docker_uuid, roi_region_name) "
                                 f"VALUES ('%s','%s','%s');") % (roi_region_id, docker_uuid, roi_region_name)
                        db_cursor.execute(sql_7)
                        mydb.commit()

                        for roi_region_coordinate_dict in roi_region_coordinate_list:
                            coordinate_x = roi_region_coordinate_dict["x"]
                            coordinate_y = roi_region_coordinate_dict["y"]

                            sql_9 = ((f"INSERT INTO video_analysis_user.region_coordinate_{license_information} "
                                      f"(roi_region_id, x, y, docker_uuid) "
                                      f"VALUES ('%s','%s','%s','%s');")
                                     % (roi_region_id, coordinate_x, coordinate_y, docker_uuid))
                            db_cursor.execute(sql_9)
                            mydb.commit()

                    if status_check == "Active" or "Active_M":
                        cmd_stop = "nsenter -m -n -t 1 docker stop " + docker_uuid
                        subprocess.Popen(
                            cmd_stop,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                        )

                        cmd_rm = "nsenter -m -n -t 1 docker rm " + docker_uuid
                        subprocess.Popen(
                            cmd_rm,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                        )

                        docker_create(docker_uuid=docker_uuid, license_information=license_information)

                        docker_operation_log(license_information=license_information,
                                             log_type="新增",
                                             device_number=device_number,
                                             channel_name=channel_name,
                                             log_action="修改参数并重新创建算法检测任务。",
                                             task_name=task_name)

                    elif status_check == "Inactive" or "Inactive_M":
                        cmd_rm = "nsenter -m -n -t 1 docker rm " + docker_uuid
                        subprocess.Popen(
                            cmd_rm,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                        )

                        docker_create(docker_uuid=docker_uuid, license_information=license_information)

                        docker_operation_log(license_information=license_information,
                                             log_type="新增",
                                             device_number=device_number,
                                             channel_name=channel_name,
                                             log_action="修改参数并重新创建算法检测任务。",
                                             task_name=task_name)

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def save_args():
    jsons = request.json

    device_number = jsons["device_number"]
    channel_name = jsons["channel_name"]
    task_name = jsons["task_name"]
    mark_position = jsons["mark_position"]
    model_path = jsons["load_model_path"]
    model_name = jsons["load_model_name"]
    model_type = jsons["load_model_type"]
    user_set_detect_device_number = jsons["set_detect_device_number"]
    user_set_detect_interval = str(jsons["set_detect_interval"])
    user_set_detect_iou = str(jsons["set_detect_iou"])
    user_set_detect_conf = str(jsons["set_detect_conf"])
    user_set_alarm_type = jsons["set_alarm_type"]
    user_set_alarm_object = jsons["set_alarm_object"]
    user_set_alarm_interval = str(jsons["set_alarm_interval"])
    user_set_roi_region = jsons["set_roi_region"]
    user_set_show_version = bool(jsons["set_show_version"])
    user_set_show_info_mark = bool(jsons["set_show_info_mark"])
    user_set_show_roi_edge = bool(jsons["set_show_roi_line"])
    user_set_show_roi_label = bool(jsons["set_show_roi_label"])
    user_set_show_fill_roi = bool(jsons["set_show_fill_roi"])
    user_set_show_fill_non_roi = bool(jsons["set_show_fill_non_roi"])
    user_set_show_result_box = bool(jsons["set_show_result_box"])
    user_set_show_result_label = bool(jsons["set_show_result_label"])
    user_set_show_result_conf = bool(jsons["set_show_result_conf"])
    user_set_show_result_count = bool(jsons["set_show_result_count"])
    base64img = jsons["base64img"]
    docker_uuid = jsons["uuid"]
    start_time = jsons["start_time"]
    stop_time = jsons["stop_time"]
    start_date = jsons["start_date"]
    stop_date = jsons["stop_date"]
    task_type = jsons["task_type"]
    docker_boot_mode = jsons["boot_mode"]
    camera_width = jsons["camera_width"]
    camera_height = jsons["camera_height"]
    operation = jsons["operation"]
    license_information = jsons["license_information"]
    connection_status = jsons["connection_status"]
    algorithm_id = jsons["algorithm_id"]
    ip_addr = jsons["ip_addr"]
    custom_name = jsons["custom_name"]

    if len(license_information) > 43:
        license_information = license_information[:43]
    license_information = license_information.replace("-", "_")

    rtsp_addr = get_rtsp()
    status = "Null"

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        if docker_uuid == "":

            docker_uuid = str(uuid.uuid4())

            sql_create_docker_args = (f"CREATE TABLE IF NOT EXISTS "
                                      f"video_analysis_user.docker_args_{license_information} "
                                      f"(docker_uuid varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                                      f"status varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"device_number varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"channel_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"rtsp_addr varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_name varchar(50) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"mark_position varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_path varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_device_number varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_iou varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_object varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"roi_region json NULL, "
                                      f"show_version varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_info_mark varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_line varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_non_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_box varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_count varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"base64img text "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, "
                                      f"boot_mode varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"docker_port varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"camera_width int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"camera_height int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"operation varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"ip_addr varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"custom_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"normal_update_time varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"sequence_number int(11) "
                                      f"NOT NULL AUTO_INCREMENT PRIMARY KEY) "
                                      f"ENGINE = InnoDB "
                                      f"CHARACTER SET = utf8mb4 "
                                      f"COLLATE = utf8mb4_general_ci "
                                      f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_docker_args)
            mydb.commit()

            sql_create_detect_device_number = (f"CREATE TABLE IF NOT EXISTS "
                                               f"video_analysis_user.detect_device_number_{license_information} "
                                               f"(id int(11) "
                                               f"NOT NULL AUTO_INCREMENT, "
                                               f"docker_uuid varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"detect_device_number varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"PRIMARY KEY (id) USING BTREE) "
                                               f"ENGINE = InnoDB "
                                               f"AUTO_INCREMENT = 95 "
                                               f"CHARACTER SET = utf8mb4 "
                                               f"COLLATE = utf8mb4_general_ci "
                                               f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_detect_device_number)
            mydb.commit()

            sql_create_alarm_object = (f"CREATE TABLE IF NOT EXISTS "
                                       f"video_analysis_user.alarm_object_{license_information} "
                                       f"(id int(11) "
                                       f"NOT NULL AUTO_INCREMENT, "
                                       f"docker_uuid varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"alarm_object varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"PRIMARY KEY (id) USING BTREE) "
                                       f"ENGINE = InnoDB "
                                       f"AUTO_INCREMENT = 67 "
                                       f"CHARACTER SET = utf8mb4 "
                                       f"COLLATE = utf8mb4_general_ci "
                                       f"ROW_FORMAT = Dynamic;")

            db_cursor.execute(sql_create_alarm_object)
            mydb.commit()

            sql_create_roi_region = (f"CREATE TABLE IF NOT EXISTS "
                                     f"video_analysis_user.roi_region_{license_information} "
                                     f"(id int(11) "
                                     f"NOT NULL AUTO_INCREMENT, "
                                     f"docker_uuid varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_id varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_name varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"PRIMARY KEY (id) USING BTREE) "
                                     f"ENGINE = InnoDB "
                                     f"AUTO_INCREMENT = 111 "
                                     f"CHARACTER SET = utf8mb4 "
                                     f"COLLATE = utf8mb4_general_ci "
                                     f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_roi_region)
            mydb.commit()

            sql_create_region_coordinate = (f"CREATE TABLE IF NOT EXISTS "
                                            f"video_analysis_user.region_coordinate_{license_information} "
                                            f"(id int(11) NOT NULL AUTO_INCREMENT, "
                                            f"docker_uuid varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"roi_region_id varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"x varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"y varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"PRIMARY KEY (id) USING BTREE) "
                                            f"ENGINE = InnoDB "
                                            f"AUTO_INCREMENT = 432 "
                                            f"CHARACTER SET = utf8mb4 "
                                            f"COLLATE = utf8mb4_general_ci "
                                            f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_region_coordinate)
            mydb.commit()

            sql = (
                      f"INSERT INTO video_analysis_user.docker_args_{license_information} "
                      f"(docker_uuid, status, start_time, stop_time, start_date, stop_date, device_number, "
                      f"channel_name, rtsp_addr, task_name, task_type, mark_position, model_path, model_name, "
                      f"model_type, detect_interval, detect_iou, detect_conf, alarm_type, alarm_interval, "
                      f"show_version, show_info_mark, show_roi_line, show_roi_label, show_fill_roi, show_fill_non_roi, "
                      f"show_result_box, show_result_label, show_result_conf, show_result_count, base64img, boot_mode, "
                      f"camera_width, camera_height, operation, ip_addr, custom_name) "
                      f"VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',"
                      f"'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',"
                      f"'%s');"
                  ) % (
                      docker_uuid,
                      status,
                      start_time,
                      stop_time,
                      start_date,
                      stop_date,
                      device_number,
                      channel_name,
                      rtsp_addr,
                      task_name,
                      task_type,
                      mark_position,
                      model_path,
                      model_name,
                      model_type,
                      user_set_detect_interval,
                      user_set_detect_iou,
                      user_set_detect_conf,
                      user_set_alarm_type,
                      user_set_alarm_interval,
                      user_set_show_version,
                      user_set_show_info_mark,
                      user_set_show_roi_edge,
                      user_set_show_roi_label,
                      user_set_show_fill_roi,
                      user_set_show_fill_non_roi,
                      user_set_show_result_box,
                      user_set_show_result_label,
                      user_set_show_result_conf,
                      user_set_show_result_count,
                      base64img,
                      docker_boot_mode,
                      camera_width,
                      camera_height,
                      operation,
                      ip_addr,
                      custom_name
                  )
            db_cursor.execute(sql)
            mydb.commit()

            for ddn in user_set_detect_device_number:
                sql_2 = (f"INSERT INTO video_analysis_user.detect_device_number_{license_information} "
                         f"(docker_uuid, detect_device_number) "
                         f"VALUES ('%s','%s');") % (docker_uuid, ddn)
                db_cursor.execute(sql_2)
                mydb.commit()

            for ao in user_set_alarm_object:
                sql_3 = (f"INSERT INTO video_analysis_user.alarm_object_{license_information} "
                         f"(docker_uuid, alarm_object) "
                         f"VALUES ('%s','%s');") % (docker_uuid, ao)
                db_cursor.execute(sql_3)
                mydb.commit()

            for rr_dict in user_set_roi_region:
                roi_region_name = rr_dict["set_roi_region_name"]
                roi_region_coordinate_list = rr_dict["set_roi_region_coordinate"]

                roi_region_id = uuid.uuid4()

                sql_4 = ((f"INSERT INTO video_analysis_user.roi_region_{license_information} "
                          f"(roi_region_id, docker_uuid, roi_region_name) "
                          f"VALUES ('%s','%s','%s');")
                         % (roi_region_id, docker_uuid, roi_region_name))
                db_cursor.execute(sql_4)
                mydb.commit()

                for roi_region_coordinate_dict in roi_region_coordinate_list:
                    coordinate_x = roi_region_coordinate_dict["x"]
                    coordinate_y = roi_region_coordinate_dict["y"]
                    sql_5 = ((f"INSERT INTO video_analysis_user.region_coordinate_{license_information} "
                              f"(roi_region_id, x, y, docker_uuid) "
                              f"VALUES ('%s','%s','%s','%s');")
                             % (roi_region_id, coordinate_x, coordinate_y, docker_uuid))
                    db_cursor.execute(sql_5)
                    mydb.commit()

            if connection_status == "False":
                state_information = "inactive"
                sql_change_algorithm_state = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                              f"SET state_information='%s' "
                                              f"WHERE id='%s';") % (state_information, algorithm_id)
                db_cursor.execute(sql_change_algorithm_state)
                mydb.commit()

                sql_change_algorithm_docker_uuid = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                                    f"SET docker_uuid='%s' "
                                                    f"WHERE id='%s';") % (docker_uuid, algorithm_id)
                db_cursor.execute(sql_change_algorithm_docker_uuid)
                mydb.commit()

        elif docker_uuid != "":
            sql = (
                    f"UPDATE video_analysis_user.docker_args_{license_information} "
                    f"SET start_time='%s', stop_time='%s', start_date='%s', stop_date='%s', task_name='%s', "
                    f"task_type='%s', mark_position='%s', model_path='%s', model_name='%s', model_type='%s', "
                    f"detect_interval='%s', detect_iou='%s', detect_conf='%s', alarm_type='%s', alarm_interval='%s', "
                    f"show_version='%s', show_info_mark='%s', show_roi_line='%s', show_roi_label='%s', "
                    f"show_fill_roi='%s', show_fill_non_roi='%s', show_result_box='%s', show_result_label='%s', "
                    f"show_result_conf='%s', show_result_count='%s', base64img='%s', boot_mode='%s', "
                    f"camera_width='%s', camera_height='%s', operation='%s', ip_addr='%s', custom_name='%s' "
                    f"WHERE docker_uuid='%s';"
                    % (
                        start_time,
                        stop_time,
                        start_date,
                        stop_date,
                        task_name,
                        task_type,
                        mark_position,
                        model_path,
                        model_name,
                        model_type,
                        user_set_detect_interval,
                        user_set_detect_iou,
                        user_set_detect_conf,
                        user_set_alarm_type,
                        user_set_alarm_interval,
                        user_set_show_version,
                        user_set_show_info_mark,
                        user_set_show_roi_edge,
                        user_set_show_roi_label,
                        user_set_show_fill_roi,
                        user_set_show_fill_non_roi,
                        user_set_show_result_box,
                        user_set_show_result_label,
                        user_set_show_result_conf,
                        user_set_show_result_count,
                        base64img,
                        docker_boot_mode,
                        camera_width,
                        camera_height,
                        operation,
                        ip_addr,
                        custom_name,
                        docker_uuid
                    )
            )
            db_cursor.execute(sql)
            mydb.commit()

            sql_2 = (f"DELETE FROM video_analysis_user.detect_device_number_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_2)
            mydb.commit()

            for ddn in user_set_detect_device_number:
                sql_3 = (f"INSERT INTO video_analysis_user.detect_device_number_{license_information} "
                         f"(docker_uuid, detect_device_number) "
                         f"VALUES ('%s','%s');") % (docker_uuid, ddn)
                db_cursor.execute(sql_3)
                mydb.commit()

            sql_4 = (f"DELETE FROM video_analysis_user.alarm_object_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_4)
            mydb.commit()

            for ao in user_set_alarm_object:

                sql_5 = (f"INSERT INTO video_analysis_user.alarm_object_{license_information} "
                         f"(docker_uuid, alarm_object) "
                         f"VALUES ('%s','%s');" % (docker_uuid, ao))
                db_cursor.execute(sql_5)
                mydb.commit()

            sql_6 = (f"DELETE FROM video_analysis_user.roi_region_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_6)
            mydb.commit()

            sql_8 = (f"DELETE FROM video_analysis_user.region_coordinate_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_8)
            mydb.commit()

            for rr_dict in user_set_roi_region:
                roi_region_name = rr_dict["set_roi_region_name"]
                roi_region_coordinate_list = rr_dict["set_roi_region_coordinate"]

                roi_region_id = uuid.uuid4()

                sql_7 = (f"INSERT INTO video_analysis_user.roi_region_{license_information} "
                         f"(roi_region_id, docker_uuid, roi_region_name) "
                         f"VALUES ('%s','%s','%s');") % (roi_region_id, docker_uuid, roi_region_name)
                db_cursor.execute(sql_7)
                mydb.commit()

                for roi_region_coordinate_dict in roi_region_coordinate_list:
                    coordinate_x = roi_region_coordinate_dict["x"]
                    coordinate_y = roi_region_coordinate_dict["y"]

                    sql_9 = ((f"INSERT INTO video_analysis_user.region_coordinate_{license_information} "
                              f"(roi_region_id, x, y, docker_uuid) "
                              f"VALUES ('%s','%s','%s','%s');")
                             % (roi_region_id, coordinate_x, coordinate_y, docker_uuid))
                    db_cursor.execute(sql_9)
                    mydb.commit()

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def judge_operation():
    jsons = request.json
    operation = jsons["operation"]

    if operation == "save":
        return save_args()
    elif operation == "process":
        return process_args()


def query_args():
    jsons = request.json
    device_number = jsons["device_number"]
    license_information = jsons["license_information"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information_check = copy.deepcopy(license_information)
    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_check = ("SELECT license_information FROM license_information_all WHERE license_information='%s';"
                     % license_information_check)
        db_cursor.execute(sql_check)
        mydb.commit()
        check_result = db_cursor.fetchone()

        if check_result is None:
            sql_insert_license = ("INSERT INTO license_information_all (license_information) VALUES ('%s');"
                                  % license_information_check)
            db_cursor.execute(sql_insert_license)
            mydb.commit()

            sql_create_docker_args = (f"CREATE TABLE IF NOT EXISTS "
                                      f"video_analysis_user.docker_args_{license_information} "
                                      f"(docker_uuid varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                                      f"status varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_time varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"start_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"stop_date varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"device_number varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"channel_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"rtsp_addr varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_name varchar(50) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"task_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"mark_position varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_path varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"model_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_device_number varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_iou varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"detect_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_type varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_object varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"alarm_interval varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"roi_region json "
                                      f"NULL, "
                                      f"show_version varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_info_mark varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_line varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_roi_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_fill_non_roi varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_box varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_label varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_conf varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"show_result_count varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"base64img text "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL, "
                                      f"boot_mode varchar(20) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"docker_port varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"camera_width int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"camera_height int(11) "
                                      f"NULL DEFAULT NULL, "
                                      f"operation varchar(10) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"ip_addr varchar(30) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"custom_name varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"normal_update_time varchar(100) "
                                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                      f"sequence_number int(11) "
                                      f"NOT NULL AUTO_INCREMENT PRIMARY KEY)"
                                      f"ENGINE = InnoDB "
                                      f"CHARACTER SET = utf8mb4 "
                                      f"COLLATE = utf8mb4_general_ci "
                                      f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_docker_args)
            mydb.commit()

            sql_create_detect_device_number = (f"CREATE TABLE IF NOT EXISTS "
                                               f"video_analysis_user.detect_device_number_{license_information} "
                                               f"(id int(11) "
                                               f"NOT NULL AUTO_INCREMENT, "
                                               f"docker_uuid varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"detect_device_number varchar(100) "
                                               f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                               f"PRIMARY KEY (id) USING BTREE) "
                                               f"ENGINE = InnoDB "
                                               f"AUTO_INCREMENT = 95 "
                                               f"CHARACTER SET = utf8mb4 "
                                               f"COLLATE = utf8mb4_general_ci "
                                               f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_detect_device_number)
            mydb.commit()

            sql_create_alarm_object = (f"CREATE TABLE IF NOT EXISTS "
                                       f"video_analysis_user.alarm_object_{license_information} "
                                       f"(id int(11) "
                                       f"NOT NULL AUTO_INCREMENT, "
                                       f"docker_uuid varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"alarm_object varchar(100) "
                                       f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                       f"PRIMARY KEY (id) USING BTREE) "
                                       f"ENGINE = InnoDB "
                                       f"AUTO_INCREMENT = 67 "
                                       f"CHARACTER SET = utf8mb4 "
                                       f"COLLATE = utf8mb4_general_ci "
                                       f"ROW_FORMAT = Dynamic;")

            db_cursor.execute(sql_create_alarm_object)
            mydb.commit()

            sql_create_roi_region = (f"CREATE TABLE IF NOT EXISTS "
                                     f"video_analysis_user.roi_region_{license_information} "
                                     f"(id int(11) "
                                     f"NOT NULL AUTO_INCREMENT, "
                                     f"docker_uuid varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_id varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"roi_region_name varchar(100) "
                                     f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                     f"PRIMARY KEY (id) USING BTREE) "
                                     f"ENGINE = InnoDB "
                                     f"AUTO_INCREMENT = 111 "
                                     f"CHARACTER SET = utf8mb4 "
                                     f"COLLATE = utf8mb4_general_ci "
                                     f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_roi_region)
            mydb.commit()

            sql_create_region_coordinate = (f"CREATE TABLE IF NOT EXISTS "
                                            f"video_analysis_user.region_coordinate_{license_information} "
                                            f"(id int(11) NOT NULL AUTO_INCREMENT, "
                                            f"docker_uuid varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"roi_region_id varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"x varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"y varchar(100) "
                                            f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                                            f"PRIMARY KEY (id) USING BTREE) "
                                            f"ENGINE = InnoDB "
                                            f"AUTO_INCREMENT = 432 "
                                            f"CHARACTER SET = utf8mb4 "
                                            f"COLLATE = utf8mb4_general_ci "
                                            f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create_region_coordinate)
            mydb.commit()

            sql_create = (f"CREATE TABLE IF NOT EXISTS "
                          f"video_analysis_user.algorithm_{license_information} "
                          f"(id varchar(36) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"algorithm_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"task_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"model_path varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"model_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"model_type varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"alarm_object_name varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"ico varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"authorization_status varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                          f"license_information varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"connection_status varchar(10) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"state_information varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"docker_uuid varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"object varchar(100) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,"
                          f"version varchar(20) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"update_available varchar(10) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"md5 varchar(32) "
                          f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                          f"sequence_number int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY) "
                          f"ENGINE = InnoDB "
                          f"CHARACTER SET = utf8mb4 "
                          f"COLLATE = utf8mb4_general_ci "
                          f"ROW_FORMAT = Dynamic;")
            db_cursor.execute(sql_create)
            mydb.commit()

            time.sleep(0.5)

            sql_copy = (f"INSERT INTO video_analysis_user.algorithm_{license_information} "
                        f"(id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, ico, "
                        f"authorization_status, license_information, connection_status, state_information, "
                        f"docker_uuid, object) "
                        f"SELECT id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, "
                        f"ico, authorization_status, license_information, connection_status, state_information, "
                        f"docker_uuid, object "
                        f"FROM video_analysis.algorithm;")
            db_cursor.execute(sql_copy)
            mydb.commit()

            time.sleep(0.5)

        else:
            pass

        # sql_search = (f"SELECT DISTINCT docker_uuid FROM video_analysis_user.docker_args_{license_information} "
        #               f"WHERE device_number='%s' "
        #               f"ORDER BY sequence_number DESC;") % device_number

        sql_search = (f"SELECT docker_uuid FROM video_analysis_user.docker_args_{license_information} "
                      f"WHERE device_number='%s' "
                      f"ORDER BY sequence_number DESC;") % device_number
        db_cursor.execute(sql_search)
        mydb.commit()
        data_1 = db_cursor.fetchall()

        jsons_query = []

        if len(data_1) == 0:
            return jsonify(
                msg="success",
                code=0,
                data=[]
            )

        for docker_uuid_dict in data_1:
            docker_uuid = docker_uuid_dict[0]

            sql_1 = (f"SELECT docker_uuid, status, start_time, stop_time, start_date, stop_date, device_number, "
                     f"channel_name, rtsp_addr, task_name, task_type, mark_position, model_path, model_name, "
                     f"model_type, detect_interval, detect_iou, detect_conf, alarm_type, alarm_interval, show_version, "
                     f"show_info_mark, show_roi_line, show_roi_label, show_fill_roi, show_fill_non_roi, "
                     f"show_result_box, show_result_label, show_result_conf, show_result_count, base64img, boot_mode, "
                     f"camera_width, camera_height, operation, custom_name, docker_port "
                     f"FROM video_analysis_user.docker_args_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_1)
            mydb.commit()
            args_0 = db_cursor.fetchone()
            args_1 = list(args_0)

            sql_2 = (f"SELECT detect_device_number FROM video_analysis_user.detect_device_number_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_2)
            mydb.commit()
            args_2 = db_cursor.fetchall()

            detect_device_number = []

            for ddn in args_2:
                ddn_str = str(ddn[0])
                detect_device_number.append(ddn_str)

            sql_3 = (f"SELECT alarm_object FROM video_analysis_user.alarm_object_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_3)
            mydb.commit()
            args_3 = db_cursor.fetchall()

            alarm_object = []

            for ao in args_3:
                ao_str = ao[0]
                alarm_object.append(ao_str)

            alarm_object_list = []

            for alarm_object_english in alarm_object:
                sql_ce = "SELECT object FROM object WHERE alarm_object_name='%s';" % alarm_object_english
                db_cursor.execute(sql_ce)
                mydb.commit()
                args_ce = db_cursor.fetchone()

                if args_ce is None:
                    sql_ce_o = (f"SELECT object FROM video_analysis_user.algorithm_{license_information} "
                                f"WHERE alarm_object_name='%s';") % alarm_object_english
                    db_cursor.execute(sql_ce_o)
                    mydb.commit()
                    args_ce_o = db_cursor.fetchone()

                    alarm_json = {"alarm_object_name": alarm_object_english, "object": args_ce_o[0]}
                    alarm_object_list.append(alarm_json)
                else:
                    alarm_json = {"alarm_object_name": alarm_object_english, "object": args_ce[0]}
                    alarm_object_list.append(alarm_json)

            sql_4 = (f"SELECT roi_region_name, roi_region_id FROM video_analysis_user.roi_region_{license_information} "
                     f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_4)
            mydb.commit()
            args_4 = db_cursor.fetchall()

            set_roi_region = []

            for rr in args_4:
                roi_region_name = rr[0]
                roi_region_id = rr[1]
                sql_5 = (f"SELECT x, y FROM video_analysis_user.region_coordinate_{license_information} "
                         f"WHERE roi_region_id='%s';") % roi_region_id
                db_cursor.execute(sql_5)
                mydb.commit()
                args_5 = db_cursor.fetchall()

                region_coordinate = []

                for xy in args_5:
                    x = xy[0]
                    y = xy[1]
                    new_coordinate = {"x": f"{x}", "y": f"{y}"}
                    region_coordinate.append(new_coordinate)

                roi_region = {"set_roi_region_name": f"{roi_region_name}",
                              "set_roi_region_coordinate": region_coordinate}
                set_roi_region.append(roi_region)

            sql_query_algorithm_id = (f"SELECT id, connection_status "
                                      f"FROM video_analysis_user.algorithm_{license_information} "
                                      f"WHERE docker_uuid='%s';") % docker_uuid
            db_cursor.execute(sql_query_algorithm_id)
            mydb.commit()
            algorithm_args = db_cursor.fetchone()

            if algorithm_args is None:
                sql_query_algorithm_id = (f"SELECT id, connection_status "
                                          f"FROM video_analysis_user.algorithm_{license_information} "
                                          f"WHERE algorithm_name='%s';") % args_1[9]
                db_cursor.execute(sql_query_algorithm_id)
                mydb.commit()
                algorithm_args = db_cursor.fetchone()

            for i in range(0, 37):
                if args_1[i] == "False":
                    args_1[i] = ""

            jsons_part = {
                "uuid": args_1[0],
                'status': args_1[1],
                'start_time': args_1[2],
                'stop_time': args_1[3],
                'start_date': args_1[4],
                'stop_date': args_1[5],
                "device_number": args_1[6],
                "channel_name": args_1[7],
                "rtsp_addr": args_1[8],
                "task_name": args_1[9],
                "task_type": args_1[10],
                "mark_position": args_1[11],
                "load_model_path": args_1[12],
                "load_model_name": args_1[13],
                "load_model_type": args_1[14],
                "set_detect_device_number": detect_device_number,
                "set_detect_interval": int(args_1[15]),
                "set_detect_iou": float(args_1[16]),
                "set_detect_conf": float(args_1[17]),
                "set_alarm_type": args_1[18],
                "set_alarm_object": alarm_object_list,
                "set_alarm_interval": int(args_1[19]),
                "set_roi_region": set_roi_region,
                "set_show_version": bool(args_1[20]),
                "set_show_info_mark": bool(args_1[21]),
                "set_show_roi_line": bool(args_1[22]),
                "set_show_roi_label": bool(args_1[23]),
                "set_show_fill_roi": bool(args_1[24]),
                "set_show_fill_non_roi": bool(args_1[25]),
                "set_show_result_box": bool(args_1[26]),
                "set_show_result_label": bool(args_1[27]),
                "set_show_result_conf": bool(args_1[28]),
                "set_show_result_count": bool(args_1[29]),
                "base64img": args_1[30],
                "boot_mode": args_1[31],
                "camera_width": args_1[32],
                "camera_height": args_1[33],
                "operation": args_1[34],
                "custom_name": args_1[35],
                "docker_port": args_1[36],
                "algorithm_id": algorithm_args[0],
                "connection_status": algorithm_args[1]
            }

            jsons_query.append(jsons_part)
            # print(jsons_query)
            # query_result = json.dumps(jsons_query)

    except Exception as e:
        print(e)
        logging.debug(e)

        return jsonify(
            msg="Server Internal Error",
            code=1,
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0,
        data=jsons_query
    )


def timer():
    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    now_time = str(datetime.datetime.now().time().strftime("%H:%M"))
    now_date = datetime.datetime.now().date()

    try:
        sql_license = "SELECT license_information FROM license_information_all;"
        db_cursor.execute(sql_license)
        mydb.commit()
        license_tuple_list = db_cursor.fetchall()

        for license_tuple in license_tuple_list:
            license_information = license_tuple[0]
            license_information = license_information.replace("-", "_")

            sql_query = (f"SELECT docker_uuid, status, start_time, stop_time, start_date, stop_date "
                         f"FROM video_analysis_user.docker_args_{license_information} "
                         f"WHERE status='Active' OR status='Inactive';")
            db_cursor.execute(sql_query)
            mydb.commit()
            docker_list = db_cursor.fetchall()

            for docker_part in docker_list:
                docker_uuid = docker_part[0]
                status = docker_part[1]
                start_time = docker_part[2]
                stop_time = docker_part[3]
                start_date = docker_part[4]
                stop_date = docker_part[5]

                start_date = pandas.to_datetime(start_date).date()

                if start_time == "00:00" and stop_time == "00:00":
                    if stop_date != "forever":
                        stop_date = pandas.to_datetime(stop_time).date()
                        if now_date < start_date:
                            if status == "Active":
                                docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                sql_log = (f"SELECT device_number, channel_name, task_name "
                                           f"FROM video_analysis_user.docker_args_{license_information} "
                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_log)
                                log_tuple = db_cursor.fetchone()

                                device_number = log_tuple[0]
                                channel_name = log_tuple[1]
                                task_name = log_tuple[2]

                                docker_operation_log(license_information=license_information,
                                                     log_type="停止",
                                                     device_number=device_number,
                                                     channel_name=channel_name,
                                                     log_action="定时器自动停止任务。",
                                                     task_name=task_name)

                                sql_update_inactive = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                       f"SET status='Inactive' "
                                                       f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_update_inactive)
                                mydb.commit()
                            elif status == "Inactive":
                                pass
                        if start_date <= now_date <= stop_date:
                            if status == "Active":
                                pass
                            elif status == "Inactive":
                                docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                sql_log = (f"SELECT device_number, channel_name, task_name "
                                           f"FROM video_analysis_user.docker_args_{license_information} "
                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_log)
                                log_tuple = db_cursor.fetchone()

                                device_number = log_tuple[0]
                                channel_name = log_tuple[1]
                                task_name = log_tuple[2]

                                docker_operation_log(license_information=license_information,
                                                     log_type="启动",
                                                     device_number=device_number,
                                                     channel_name=channel_name,
                                                     log_action="定时器自动启动任务。",
                                                     task_name=task_name)

                                sql_update_active = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                     f"SET status='Active' "
                                                     f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_update_active)
                                mydb.commit()

                                sql_docker_port = (f"SELECT docker_port "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_docker_port)
                                mydb.commit()
                                docker_port_tuple = db_cursor.fetchone()
                                docker_port = str(docker_port_tuple[0])

                                sql_task_number = (f"SELECT task_type "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_task_number)
                                mydb.commit()
                                task_number_tuple = db_cursor.fetchone()
                                task_number = str(task_number_tuple[0])

                                sql_ip = (f"SELECT ip_addr FROM video_analysis_user.docker_args_{license_information} "
                                          f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_ip)
                                mydb.commit()
                                ip_addr_tuple = db_cursor.fetchone()
                                ip_addr = ip_addr_tuple[0]

                                deliver_args(
                                    jsons=get_db_args(docker_uuid=docker_uuid, license_information=license_information),
                                    suburl=task_classify(type_number=task_number),
                                    port=docker_port,
                                    ip=ip_addr
                                )
                        if now_date > stop_date:
                            if status == "Active":
                                docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                sql_log = (f"SELECT device_number, channel_name, task_name "
                                           f"FROM video_analysis_user.docker_args_{license_information} "
                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_log)
                                log_tuple = db_cursor.fetchone()

                                device_number = log_tuple[0]
                                channel_name = log_tuple[1]
                                task_name = log_tuple[2]

                                docker_operation_log(license_information=license_information,
                                                     log_type="停止",
                                                     device_number=device_number,
                                                     channel_name=channel_name,
                                                     log_action="定时器自动停止任务。",
                                                     task_name=task_name)

                                sql_update_inactive = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                       f"SET status='Inactive' "
                                                       f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_update_inactive)
                                mydb.commit()
                            elif status == "Inactive":
                                pass
                    elif stop_date == "forever":
                        if now_date < start_date:
                            if status == "Active":
                                docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                sql_log = (f"SELECT device_number, channel_name, task_name "
                                           f"FROM video_analysis_user.docker_args_{license_information} "
                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_log)
                                log_tuple = db_cursor.fetchone()

                                device_number = log_tuple[0]
                                channel_name = log_tuple[1]
                                task_name = log_tuple[2]

                                docker_operation_log(license_information=license_information,
                                                     log_type="停止",
                                                     device_number=device_number,
                                                     channel_name=channel_name,
                                                     log_action="定时器自动停止任务。",
                                                     task_name=task_name)

                                sql_update_inactive = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                       f"SET status='Inactive' "
                                                       f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_update_inactive)
                                mydb.commit()
                            elif status == "Inactive":
                                pass
                        if now_date >= start_date:
                            if status == "Active":
                                pass
                            elif status == "Inactive":
                                docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                sql_log = (f"SELECT device_number, channel_name, task_name "
                                           f"FROM video_analysis_user.docker_args_{license_information} "
                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_log)
                                log_tuple = db_cursor.fetchone()

                                device_number = log_tuple[0]
                                channel_name = log_tuple[1]
                                task_name = log_tuple[2]

                                docker_operation_log(license_information=license_information,
                                                     log_type="启动",
                                                     device_number=device_number,
                                                     channel_name=channel_name,
                                                     log_action="定时器自动启动任务。",
                                                     task_name=task_name)

                                sql_update_active = (f"UPDATE video_analysis_user.docker_args_{license_information} "
                                                     f"SET status='Active' "
                                                     f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_update_active)
                                mydb.commit()

                                sql_docker_port = (f"SELECT docker_port "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_docker_port)
                                mydb.commit()
                                docker_port_tuple = db_cursor.fetchone()
                                docker_port = str(docker_port_tuple[0])

                                sql_task_number = (f"SELECT task_type "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_task_number)
                                mydb.commit()
                                task_number_tuple = db_cursor.fetchone()
                                task_number = str(task_number_tuple[0])

                                sql_ip = (f"SELECT ip_addr "
                                          f"FROM video_analysis_user.docker_args_{license_information} "
                                          f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_ip)
                                mydb.commit()
                                ip_addr_tuple = db_cursor.fetchone()
                                ip_addr = ip_addr_tuple[0]

                                deliver_args(
                                    jsons=get_db_args(docker_uuid=docker_uuid, license_information=license_information),
                                    suburl=task_classify(type_number=task_number),
                                    port=docker_port,
                                    ip=ip_addr
                                )
                else:
                    if stop_time != "00:00":
                        start_time = pandas.to_datetime(start_time).time().strftime("%H%M")
                        stop_time = pandas.to_datetime(stop_time).time().strftime("%H%M")
                        if stop_date != "forever":
                            stop_date = pandas.to_datetime(stop_time).date()
                            if now_date < start_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                            if start_date <= now_date <= stop_date:
                                if start_time <= now_time < stop_time:
                                    if status == "Active":
                                        pass
                                    elif status == "Inactive":
                                        docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="启动",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动启动任务。",
                                                             task_name=task_name)

                                        sql_update_active = (f"UPDATE "
                                                             f"video_analysis_user.docker_args_{license_information} "
                                                             f"SET status='Active' "
                                                             f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_active)
                                        mydb.commit()

                                        sql_docker_port = (f"SELECT docker_port "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_docker_port)
                                        mydb.commit()
                                        docker_port_tuple = db_cursor.fetchone()
                                        docker_port = str(docker_port_tuple[0])

                                        sql_task_number = (f"SELECT task_type "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_task_number)
                                        mydb.commit()
                                        task_number_tuple = db_cursor.fetchone()
                                        task_number = str(task_number_tuple[0])

                                        sql_ip = (f"SELECT ip_addr "
                                                  f"FROM "
                                                  f"video_analysis_user.docker_args_{license_information} "
                                                  f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_ip)
                                        mydb.commit()
                                        ip_addr_tuple = db_cursor.fetchone()
                                        ip_addr = ip_addr_tuple[0]

                                        deliver_args(
                                            jsons=get_db_args(
                                                docker_uuid=docker_uuid,
                                                license_information=license_information),
                                            suburl=task_classify(type_number=task_number),
                                            port=docker_port,
                                            ip=ip_addr
                                        )
                                if now_time >= stop_time:
                                    if status == "Active":
                                        docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="停止",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动停止任务。",
                                                             task_name=task_name)

                                        sql_update_inactive = (f"UPDATE "
                                                               f"video_analysis_user.docker_args_{license_information} "
                                                               f"SET status='Inactive' "
                                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_inactive)
                                        mydb.commit()
                                    elif status == "Inactive":
                                        pass
                            if now_date > stop_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                        elif stop_date == "forever":
                            if now_date < start_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                            if now_date >= start_date:
                                if start_time <= now_time < stop_time:
                                    if status == "Active":
                                        pass
                                    elif status == "Inactive":
                                        docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="启动",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动启动任务。",
                                                             task_name=task_name)

                                        sql_update_active = (f"UPDATE "
                                                             f"video_analysis_user.docker_args_{license_information} "
                                                             f"SET status='Active' "
                                                             f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_active)
                                        mydb.commit()

                                        sql_docker_port = (f"SELECT docker_port "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_docker_port)
                                        mydb.commit()
                                        docker_port_tuple = db_cursor.fetchone()
                                        docker_port = str(docker_port_tuple[0])

                                        sql_task_number = (f"SELECT task_type "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_task_number)
                                        mydb.commit()
                                        task_number_tuple = db_cursor.fetchone()
                                        task_number = str(task_number_tuple[0])

                                        sql_ip = (f"SELECT ip_addr "
                                                  f"FROM "
                                                  f"video_analysis_user.docker_args_{license_information} "
                                                  f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_ip)
                                        mydb.commit()
                                        ip_addr_tuple = db_cursor.fetchone()
                                        ip_addr = ip_addr_tuple[0]

                                        deliver_args(
                                            jsons=get_db_args(
                                                docker_uuid=docker_uuid,
                                                license_information=license_information),
                                            suburl=task_classify(type_number=task_number),
                                            port=docker_port,
                                            ip=ip_addr
                                        )
                                if now_time >= stop_time:
                                    if status == "Active":
                                        docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="停止",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动停止任务。",
                                                             task_name=task_name)

                                        sql_update_inactive = (f"UPDATE "
                                                               f"video_analysis_user.docker_args_{license_information} "
                                                               f"SET status='Inactive' "
                                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_inactive)
                                        mydb.commit()
                                    elif status == "Inactive":
                                        pass
                    if stop_time == "00:00":
                        start_time = pandas.to_datetime(start_time).time().strftime("%H%M")
                        stop_time = pandas.to_datetime(stop_time).time().strftime("%H%M")
                        if stop_date != "forever":
                            stop_date = pandas.to_datetime(stop_time).date()
                            if now_date < start_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                            if start_date <= now_date <= stop_date:
                                if start_time <= now_time:
                                    if status == "Active":
                                        pass
                                    elif status == "Inactive":
                                        docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="启动",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动启动任务。",
                                                             task_name=task_name)

                                        sql_update_active = (f"UPDATE "
                                                             f"video_analysis_user.docker_args_{license_information} "
                                                             f"SET status='Active' "
                                                             f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_active)
                                        mydb.commit()

                                        sql_docker_port = (f"SELECT docker_port "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_docker_port)
                                        mydb.commit()
                                        docker_port_tuple = db_cursor.fetchone()
                                        docker_port = str(docker_port_tuple[0])

                                        sql_task_number = (f"SELECT task_type "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_task_number)
                                        mydb.commit()
                                        task_number_tuple = db_cursor.fetchone()
                                        task_number = str(task_number_tuple[0])

                                        sql_ip = (f"SELECT ip_addr "
                                                  f"FROM "
                                                  f"video_analysis_user.docker_args_{license_information} "
                                                  f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_ip)
                                        mydb.commit()
                                        ip_addr_tuple = db_cursor.fetchone()
                                        ip_addr = ip_addr_tuple[0]

                                        deliver_args(
                                            jsons=get_db_args(
                                                docker_uuid=docker_uuid,
                                                license_information=license_information),
                                            suburl=task_classify(type_number=task_number),
                                            port=docker_port,
                                            ip=ip_addr
                                        )
                                if now_time == stop_time:
                                    if status == "Active":
                                        docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="停止",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动停止任务。",
                                                             task_name=task_name)

                                        sql_update_inactive = (f"UPDATE "
                                                               f"video_analysis_user.docker_args_{license_information} "
                                                               f"SET status='Inactive' "
                                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_inactive)
                                        mydb.commit()
                                    elif status == "Inactive":
                                        pass
                            if now_date > stop_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                        elif stop_date == "forever":
                            if now_date < start_date:
                                if status == "Active":
                                    docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                    sql_log = (f"SELECT device_number, channel_name, task_name "
                                               f"FROM video_analysis_user.docker_args_{license_information} "
                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_log)
                                    log_tuple = db_cursor.fetchone()

                                    device_number = log_tuple[0]
                                    channel_name = log_tuple[1]
                                    task_name = log_tuple[2]

                                    docker_operation_log(license_information=license_information,
                                                         log_type="停止",
                                                         device_number=device_number,
                                                         channel_name=channel_name,
                                                         log_action="定时器自动停止任务。",
                                                         task_name=task_name)

                                    sql_update_inactive = (f"UPDATE "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"SET status='Inactive' "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                    db_cursor.execute(sql_update_inactive)
                                    mydb.commit()
                                elif status == "Inactive":
                                    pass
                            if now_date >= start_date:
                                if start_time <= now_time:
                                    if status == "Active":
                                        pass
                                    elif status == "Inactive":
                                        docker_start(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="启动",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动启动任务。",
                                                             task_name=task_name)

                                        sql_update_active = (f"UPDATE "
                                                             f"video_analysis_user.docker_args_{license_information} "
                                                             f"SET status='Active' "
                                                             f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_active)
                                        mydb.commit()

                                        sql_docker_port = (f"SELECT docker_port "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_docker_port)
                                        mydb.commit()
                                        docker_port_tuple = db_cursor.fetchone()
                                        docker_port = str(docker_port_tuple[0])

                                        sql_task_number = (f"SELECT task_type "
                                                           f"FROM "
                                                           f"video_analysis_user.docker_args_{license_information} "
                                                           f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_task_number)
                                        mydb.commit()
                                        task_number_tuple = db_cursor.fetchone()
                                        task_number = str(task_number_tuple[0])

                                        sql_ip = (f"SELECT ip_addr "
                                                  f"FROM "
                                                  f"video_analysis_user.docker_args_{license_information} "
                                                  f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_ip)
                                        mydb.commit()
                                        ip_addr_tuple = db_cursor.fetchone()
                                        ip_addr = ip_addr_tuple[0]

                                        deliver_args(
                                            jsons=get_db_args(
                                                docker_uuid=docker_uuid,
                                                license_information=license_information),
                                            suburl=task_classify(type_number=task_number),
                                            port=docker_port,
                                            ip=ip_addr
                                        )
                                if now_time == stop_time:
                                    if status == "Active":
                                        docker_stop(docker_uuid=docker_uuid, license_information=license_information)

                                        sql_log = (f"SELECT device_number, channel_name, task_name "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_log)
                                        log_tuple = db_cursor.fetchone()

                                        device_number = log_tuple[0]
                                        channel_name = log_tuple[1]
                                        task_name = log_tuple[2]

                                        docker_operation_log(license_information=license_information,
                                                             log_type="停止",
                                                             device_number=device_number,
                                                             channel_name=channel_name,
                                                             log_action="定时器自动停止任务。",
                                                             task_name=task_name)

                                        sql_update_inactive = (f"UPDATE "
                                                               f"video_analysis_user.docker_args_{license_information} "
                                                               f"SET status='Inactive' "
                                                               f"WHERE docker_uuid='%s';") % docker_uuid
                                        db_cursor.execute(sql_update_inactive)
                                        mydb.commit()
                                    elif status == "Inactive":
                                        pass
    except Exception as e:
        logging.debug('Timer Server Error:%s' % e)
    finally:
        db_cursor.close()
        mydb.close()


def algorithm_shop_list_old():
    jsons = request.json
    page = int(jsons["page"])
    limit = int(jsons["limit"])

    mydb = mysql_kv()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql = (f"SELECT id, algorithm_name, ico, introduction, cost FROM algorithm_shop "
               f"LIMIT {(page - 1) * limit}, {limit};")
        db_cursor.execute(sql)
        mydb.commit()
        shop_a_list = db_cursor.fetchall()

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0,
        data=shop_a_list
    )


def algorithm_shop_list():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)

    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )

    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )

    license_information = system_setup.main_board_info()

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql_kv()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_create = (f"CREATE TABLE IF NOT EXISTS "
                      f"video_analysis_user.algorithm_{license_information} "
                      f"(id varchar(36) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                      f"algorithm_name varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                      f"task_type varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                      f"model_path varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"model_name varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"model_type varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"alarm_object_name varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"ico varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"authorization_status varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                      f"license_information varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"connection_status varchar(10) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"state_information varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"docker_uuid varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"object varchar(100) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"version varchar(20) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"update_available varchar(10) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"md5 varchar(32) "
                      f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                      f"sequence_number int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY) "
                      f"ENGINE = InnoDB "
                      f"CHARACTER SET = utf8mb4 "
                      f"COLLATE = utf8mb4_general_ci "
                      f"ROW_FORMAT = Dynamic;")
        db_cursor.execute(sql_create)
        mydb.commit()
        jsons = request.args

        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            type = " AND type = '" + jsons.get("type") + "'" \
                if jsons.get("type") is not None else ""
            algorithm_name = " AND algorithm_name like '%" + jsons.get("algorithm_name") + "%'" \
                if jsons.get("algorithm_name") is not None else ""
            cost = " AND cost = '" + jsons.get("cost") + "'" \
                if jsons.get("cost") is not None else ""
            sql_1 = "SELECT * FROM video_analysis.algorithm_shop WHERE 1=1 " + type + algorithm_name + cost
            db_cursor.execute(sql_1)
            cur_data = db_cursor.fetchall()

            sql_2 = (f"SELECT algorithm_name, version, update_available "
                     f"FROM video_analysis_user.algorithm_{license_information} WHERE update_available='2' "
                     f"GROUP BY algorithm_name;")
            db_cursor.execute(sql_2)
            cur_data_user_update = db_cursor.fetchall()

            sql_3 = (f"SELECT algorithm_name, version, update_available "
                     f"FROM video_analysis_user.algorithm_{license_information} WHERE update_available='1' "
                     f"GROUP BY algorithm_name;")
            db_cursor.execute(sql_3)
            cur_data_user_normal = db_cursor.fetchall()

            items = []

            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}

                for user_data_update in cur_data_user_update:
                    if user_data_update['algorithm_name'] == item['algorithm_name']:
                        temp['id'] = item['id']
                        temp['algorithm_name'] = item['algorithm_name']
                        temp['ico'] = item['ico']
                        temp['introduction'] = item['introduction']
                        temp['cost'] = item['cost']
                        temp['model_url'] = item['model_url']
                        temp['version'] = item['version']
                        temp['update_available'] = user_data_update['update_available']
                        temp['user_version'] = user_data_update['version']
                        items.append(temp)

                        break

                for user_data_normal in cur_data_user_normal:
                    if user_data_normal['algorithm_name'] == item['algorithm_name']:
                        if temp == {}:
                            temp['id'] = item['id']
                            temp['algorithm_name'] = item['algorithm_name']
                            temp['ico'] = item['ico']
                            temp['introduction'] = item['introduction']
                            temp['cost'] = item['cost']
                            temp['model_url'] = item['model_url']
                            temp['version'] = item['version']
                            temp['update_available'] = user_data_normal['update_available']
                            temp['user_version'] = user_data_normal['version']
                            items.append(temp)

                            break

                if temp == {}:
                    temp['id'] = item['id']
                    temp['algorithm_name'] = item['algorithm_name']
                    temp['ico'] = item['ico']
                    temp['introduction'] = item['introduction']
                    temp['cost'] = item['cost']
                    temp['model_url'] = item['model_url']
                    temp['version'] = item['version']
                    temp['update_available'] = '1'
                    temp['user_version'] = ''
                    items.append(temp)

            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = int(limit)

            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)

        else:
            return jsonify(
                code=1,
                msg="缺少必要参数page、limit"
            )

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )

# def add_object_shop_list():
#     mydb = mysql_kv()
#     mydb.connect()
#     db_cursor = mydb.cursor()
#
#     try:
#         sql = "SELECT id, algorithm_name, ico, introduction FROM algorithm_shop WHERE add_object_number != '';"
#         db_cursor.execute(sql)
#         mydb.commit()
#         shop_o_list = db_cursor.fetchall()
#     except Exception as e:
#         print(e)
#
#         return jsonify(
#             msg="Server Internal Error",
#             code=1
#         )
#
#     finally:
#         db_cursor.close()
#         mydb.close()
#
#     return jsonify(
#         msg="success",
#         code=0,
#         data=shop_o_list
#     )


def download_progress(model_url, model_name, algorithm_name, license_information, version):
    response = requests.get(url=model_url, stream=True)
    total_size = int(response.headers.get('Content-Length', 0))

    model_file_path = r"/mnt/work/www/upload/model/" + model_name
    # model_file_path = r"/usr/local/nginx/html/upload/model/" + model_name

    algorithm_name_version = algorithm_name + " --" + version

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_query_latest_md5 = ("SELECT md5, version FROM video_analysis.algorithm_shop WHERE algorithm_name='%s';"
                                % algorithm_name)
        db_cursor.execute(sql_query_latest_md5)
        information_tuple = db_cursor.fetchone()
        latest_md5 = information_tuple[0]
        latest_version = information_tuple[1]

        sql_update_md5 = (f"UPDATE video_analysis_user.algorithm_{license_information} SET md5='%s', version='%s' "
                          f"WHERE algorithm_name='%s';") % (latest_md5, latest_version, algorithm_name)
        db_cursor.execute(sql_update_md5)
        mydb.commit()

    except Exception as e:
        print(e)

        return False

    try:
        if os.path.exists(model_file_path):
            sql_check_md5 = (f"SELECT md5 FROM video_analysis_user.algorithm_{license_information} "
                             f"WHERE algorithm_name='%s';") % algorithm_name
            db_cursor.execute(sql_check_md5)
            md5 = db_cursor.fetchone()[0]

            integrity = verify_integrity(filename=model_file_path, ori_md5=md5)

            if integrity:
                pass

            else:
                os.remove(model_file_path)

                with open(model_file_path, 'wb') as file:
                    with tqdm(total=total_size, unit='B', unit_scale=True) as progress:
                        for data in response.iter_content(262144):
                            progress.update(len(data))
                            file.write(data)
                            download_progress_percent = str(progress)

                            jsons = {}
                            jsons['data'] = download_progress_percent[:3]
                            jsons['algorithm_name'] = algorithm_name

                            web_socket.send(str(jsons).replace("'", '"'))

        else:
            with open(model_file_path, 'wb') as file:
                with tqdm(total=total_size, unit='B', unit_scale=True) as progress:
                    for data in response.iter_content(262144):
                        progress.update(len(data))
                        file.write(data)
                        download_progress_percent = str(progress)

                        jsons = {}
                        jsons['data'] = download_progress_percent[:3]
                        jsons['algorithm_name'] = algorithm_name

                        web_socket.send(str(jsons).replace("'", '"'))

    except Exception as e:
        print(e)

        docker_operation_log(license_information=license_information,
                             log_type="下载",
                             device_number="主机",
                             channel_name="主机",
                             log_action="下载" + "【" + algorithm_name_version + "】"
                                        + "算法【失败】，请检查网络连接或主机状态。",
                             task_name=algorithm_name_version)

        try:
            os.remove(model_file_path)

        except FileNotFoundError as e:
            print(e)

        return False

    try:
        sql_check_md5 = (f"SELECT md5 FROM video_analysis_user.algorithm_{license_information} "
                         f"WHERE algorithm_name='%s';") % algorithm_name
        db_cursor.execute(sql_check_md5)
        md5 = db_cursor.fetchone()[0]

    except Exception as e:
        print(e)

        return False

    finally:
        db_cursor.close()
        mydb.close()

    integrity = verify_integrity(filename=model_file_path, ori_md5=md5)

    if integrity:
        docker_operation_log(license_information=license_information,
                             log_type="下载",
                             device_number="主机",
                             channel_name="主机",
                             log_action="下载" + "【" + algorithm_name_version + "】" + "算法至本地【成功】。",
                             task_name=algorithm_name_version)

        return True

    else:
        docker_operation_log(license_information=license_information,
                             log_type="下载",
                             device_number="主机",
                             channel_name="主机",
                             log_action="下载文件完整性校验失败，请重新下载。",
                             task_name=algorithm_name_version)

        os.remove(model_file_path)

        return False


def authorization():
    jsons = request.json
    algorithm_name = jsons["algorithm_name"]
    license_information = jsons["license_information"]
    authorization_status = jsons["authorization_status"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information_check = copy.deepcopy(license_information)
    license_information = license_information.replace("-", "_")

    if authorization_status == "authorize":
        mydb = mysql()
        mydb.connect()
        db_cursor = mydb.cursor()

        try:
            sql_check = ("SELECT license_information FROM video_analysis.license_information_all "
                         "WHERE license_information='%s';"
                         % license_information_check)
            db_cursor.execute(sql_check)
            mydb.commit()
            check_result = db_cursor.fetchone()

            if check_result is None:
                sql_insert_license = ("INSERT INTO video_analysis.license_information_all (license_information) "
                                      "VALUES ('%s');"
                                      % license_information_check)
                db_cursor.execute(sql_insert_license)
                mydb.commit()

                sql_create = (f"CREATE TABLE IF NOT EXISTS "
                              f"video_analysis_user.algorithm_{license_information} "
                              f"(id varchar(36) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                              f"algorithm_name varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                              f"task_type varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                              f"model_path varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"model_name varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"model_type varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"alarm_object_name varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"ico varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"authorization_status varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, "
                              f"license_information varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"connection_status varchar(10) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"state_information varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"docker_uuid varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"object varchar(100) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"version varchar(20) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"update_available varchar(10) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"md5 varchar(32) "
                              f"CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, "
                              f"sequence_number int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY) "
                              f"ENGINE = InnoDB "
                              f"CHARACTER SET = utf8mb4 "
                              f"COLLATE = utf8mb4_general_ci "
                              f"ROW_FORMAT = Dynamic;")
                db_cursor.execute(sql_create)
                mydb.commit()

                sql_copy = (f"INSERT INTO video_analysis_user.algorithm_{license_information} "
                            f"(id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, "
                            f"ico, authorization_status, license_information, connection_status, state_information, "
                            f"docker_uuid, object) "
                            f"SELECT id, algorithm_name, task_type, model_path, model_name, model_type, "
                            f"alarm_object_name, ico, authorization_status, license_information, connection_status, "
                            f"state_information, docker_uuid, object "
                            f"FROM video_analysis.algorithm;")
                db_cursor.execute(sql_copy)
                mydb.commit()

            sql_shop = (("SELECT algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, "
                         "ico, connection_status, object, model_url, version, md5 FROM video_analysis.algorithm_shop "
                         "WHERE algorithm_name='%s';")
                        % algorithm_name)
            db_cursor.execute(sql_shop)
            mydb.commit()
            algorithm_information = db_cursor.fetchone()

            algorithm_uuid = uuid.uuid4()
            state_information = "active"

            sql_write = ((f"INSERT INTO video_analysis_user.algorithm_{license_information} "
                          f"(id, algorithm_name, task_type, model_path, model_name, model_type, alarm_object_name, "
                          f"ico, authorization_status, license_information, connection_status, state_information, "
                          f"object, version, update_available, md5) "
                          f"VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');")
                         % (algorithm_uuid,
                            algorithm_information[0],
                            algorithm_information[1],
                            algorithm_information[2],
                            algorithm_information[3],
                            algorithm_information[4],
                            algorithm_information[5],
                            algorithm_information[6],
                            authorization_status,
                            license_information,
                            algorithm_information[7],
                            state_information,
                            algorithm_information[8],
                            algorithm_information[10],
                            "1",
                            algorithm_information[11]))
            logging.debug("---sql_write---%s" % sql_write)
            db_cursor.execute(sql_write)
            mydb.commit()

            device_number = "主机"
            channel_name = "主机"
            task_name = algorithm_name

            docker_operation_log(license_information=license_information,
                                 log_type="购买",
                                 device_number=device_number,
                                 channel_name=channel_name,
                                 log_action="插件商城购买" + "【" + task_name + "】" + "算法。",
                                 task_name=task_name)

            # if os.path.exists('/mnt/work/www/upload/model/' + algorithm_information[3]):
            #     pass
            #
            # else:
            #     wget.download(url=algorithm_information[9], out='/mnt/work/www/upload/model/')

            # if os.path.exists('/usr/local/nginx/html/upload/model/' + algorithm_information[3]):
            #     pass
            #
            # else:
            #     wget.download(url=algorithm_information[9], out='/usr/local/nginx/html/upload/model/')

            download_result = download_progress(
                model_url=algorithm_information[9],
                model_name=algorithm_information[3],
                algorithm_name=algorithm_information[0],
                license_information=license_information,
                version=algorithm_information[10]
            )

        except Exception as e:
            print(e)

            return jsonify(
                msg="Server Internal Error",
                code=1,
            )

        finally:
            db_cursor.close()
            mydb.close()

        if download_result:
            return jsonify(
                msg="success",
                code=0,
            )

        else:
            return jsonify(
                msg="Download Failed",
                code=1
            )

    else:
        return jsonify(
            msg="Unauthorized Operation",
            code=1
        )


def normal_update_time():
    mydb = mysql_kv()
    mydb.connect()
    cursor = mydb.cursor()

    try:
        jsons = request.json
        docker_uuid = jsons['docker_uuid']
        license_information = jsons['license_information']

        if len(license_information) > 43:
            license_information = license_information[:43]

        normal_update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        sql = ("SELECT * FROM video_analysis_user.docker_args_" + license_information +
               " WHERE docker_uuid='" + docker_uuid + "'")
        cursor.execute(sql)
        data = cursor.fetchone()

        if 'Inactive_M' == data['status']:
            sql_i = ("UPDATE video_analysis_user.docker_args_" + license_information +
                     " SET `status` = 'Active_M',normal_update_time ='" + normal_update_time +
                     "' WHERE docker_uuid = '" + docker_uuid + "';")

        elif 'Inactive' == data['status']:
            sql_i = ("UPDATE video_analysis_user.docker_args_" + license_information +
                     " SET `status` = 'Active',normal_update_time ='" + normal_update_time +
                     "' WHERE docker_uuid = '" + docker_uuid + "';")

        else:
            sql_i = ("UPDATE video_analysis_user.docker_args_" + license_information +
                     " SET normal_update_time ='" + normal_update_time +
                     "' WHERE docker_uuid = '" + docker_uuid + "';")

        cursor.execute(sql_i)
        mydb.commit()

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        cursor.close()
        mydb.close()

    return jsonify(
        msg="success",
        code=0
    )


def detection_algorithm_normal_update_time():
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()

    try:
        license_information = system_setup.main_board_info()

        if len(license_information) > 43:
            license_information = license_information[:43]

        license_information = license_information.replace("-", "_")

        sql_docker_uuid_m = (f"SELECT docker_uuid, device_number, channel_name, task_name "
                             f"FROM video_analysis_user.docker_args_{license_information} "
                             f"WHERE `status` = 'Active_M' AND DATE_SUB(NOW(), INTERVAL 25 SECOND) > "
                             f"normal_update_time AND normal_update_time is NOT NULL;")
        cursor.execute(sql_docker_uuid_m)
        docker_uuid_tuple_m = cursor.fetchone()

        if docker_uuid_tuple_m is not None:
            docker_uuid = docker_uuid_tuple_m[0]
            device_number = docker_uuid_tuple_m[1]
            channel_name = docker_uuid_tuple_m[2]
            task_name = docker_uuid_tuple_m[3]

            cmd_stop = "nsenter -m -n -t 1 docker kill " + docker_uuid
            subprocess.Popen(
                cmd_stop, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
            )

            docker_operation_log(license_information=license_information,
                                 log_type="异常",
                                 device_number=device_number,
                                 channel_name=channel_name,
                                 log_action="意外停止/崩溃。请检查网络/硬件故障。或系统负载过高，请减少并行任务数量。",
                                 task_name=task_name)

        sql_docker_uuid = (f"SELECT docker_uuid, device_number, channel_name, task_name "
                           f"FROM video_analysis_user.docker_args_{license_information} "
                           f"WHERE `status` = 'Active' AND DATE_SUB(NOW(), INTERVAL 25 SECOND) > "
                           f"normal_update_time AND normal_update_time is NOT NULL;")
        cursor.execute(sql_docker_uuid)
        docker_uuid_tuple = cursor.fetchone()

        if docker_uuid_tuple is not None:
            docker_uuid = docker_uuid_tuple[0]
            device_number = docker_uuid_tuple[1]
            channel_name = docker_uuid_tuple[2]
            task_name = docker_uuid_tuple[3]

            cmd_stop = "nsenter -m -n -t 1 docker kill " + docker_uuid
            subprocess.Popen(
                cmd_stop, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
            )

            docker_operation_log(license_information=license_information,
                                 log_type="异常",
                                 device_number=device_number,
                                 channel_name=channel_name,
                                 log_action="意外停止/崩溃。请检查网络/硬件故障。或系统负载过高，请减少并行任务数量。",
                                 task_name=task_name)

        sql_m = ("UPDATE video_analysis_user.docker_args_"
                 + license_information
                 + " SET `status` = 'Inactive_M' WHERE `status` = 'Active_M' AND DATE_SUB(NOW(), INTERVAL 25 SECOND) > "
                   "normal_update_time AND normal_update_time is NOT NULL;")
        cursor.execute(sql_m)
        mydb.commit()

        sql = ("UPDATE video_analysis_user.docker_args_"
               + license_information
               + " SET `status` = 'Inactive' WHERE `status` = 'Active' AND DATE_SUB(NOW(), INTERVAL 25 SECOND) > "
                 "normal_update_time AND normal_update_time is NOT NULL;")
        cursor.execute(sql)
        mydb.commit()

    except Exception as e:
        print(e)

    finally:
        cursor.close()
        mydb.close()


def model_file():
    try:
        jsons = request.json
        docker_port = jsons['docker_port']
        ip_addr = jsons['ip_addr']
        headers = {
            "Content-Type": "application/json; charset=UTF-8",
            "Referer": "http://jinbao.pinduoduo.com/index?page=5",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) "
                          "AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/67.0.3396.87 "
                          "Safari/537.36",
        }
        url = ip_addr + ":" + docker_port + "/model_file"
        response = requests.post(url, data=json.dumps(jsons), headers=headers,timeout=5).text
        response = json.loads(response)

        if response['code'] == 0:
            return jsonify(
                msg="success",
                code=0,
                data=response['data']
            )

        else:
            return jsonify(
                msg=response['msg'],
                code=1
            )

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )


def set_clean_date():
    jsons = request.json
    clean_date = jsons['clean_date']
    license_information = jsons['license_information']

    clean_date = int(clean_date)

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_create = (f"CREATE TABLE IF NOT EXISTS "
                      f"video_analysis_user.other_args_{license_information} "
                      f"(id varchar(10) NOT NULL PRIMARY KEY , "
                      f"clean_date int(11) "
                      f"NULL DEFAULT NULL) "
                      f"ENGINE = InnoDB "
                      f"CHARACTER SET = utf8mb4 "
                      f"COLLATE = utf8mb4_general_ci "
                      f"ROW_FORMAT = Dynamic;")
        db_cursor.execute(sql_create)
        mydb.commit()

        time.sleep(0.5)

        sql_query = f"SELECT clean_date FROM video_analysis_user.other_args_{license_information};"
        db_cursor.execute(sql_query)
        query_result = db_cursor.fetchone()

        if query_result is None:
            date_id = "date"
            sql = (f"INSERT INTO video_analysis_user.other_args_{license_information} (id, clean_date) "
                   f"VALUES ('%s','%s');") % (date_id, clean_date)
            db_cursor.execute(sql)
            mydb.commit()

        else:
            sql = (f"UPDATE video_analysis_user.other_args_{license_information} "
                   f"SET clean_date='%s' WHERE id='date';") % clean_date
            db_cursor.execute(sql)
            mydb.commit()

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        code=0,
        msg="success"
    )


def query_clean_date():
    jsons = request.json
    license_information = jsons["license_information"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_create = (f"CREATE TABLE IF NOT EXISTS "
                      f"video_analysis_user.other_args_{license_information} "
                      f"(id varchar(10) NOT NULL PRIMARY KEY , "
                      f"clean_date int(11) "
                      f"NULL DEFAULT NULL) "
                      f"ENGINE = InnoDB "
                      f"CHARACTER SET = utf8mb4 "
                      f"COLLATE = utf8mb4_general_ci "
                      f"ROW_FORMAT = Dynamic;")
        db_cursor.execute(sql_create)
        mydb.commit()

        sql = f"SELECT clean_date FROM video_analysis_user.other_args_{license_information} WHERE id='date';"
        db_cursor.execute(sql)
        mydb.commit()
        clean_date_tuple = db_cursor.fetchone()

        if clean_date_tuple is not None:
            clean_date = clean_date_tuple[0]

        else:
            clean_date = 30

            sql_default_date = (f"INSERT INTO video_analysis_user.other_args_{license_information} (id, clean_date) "
                                f"VALUES ('date', 30);")
            db_cursor.execute(sql_default_date)
            mydb.commit()

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        code=0,
        msg="success",
        data=clean_date
    )


def clean_alarm_pic():
    clean_date = None

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        license_information = system_setup.main_board_info()

        if len(license_information) > 43:
            license_information = license_information[:43]

        license_information = license_information.replace("-", "_")

        sql = f"SELECT clean_date FROM video_analysis_user.other_args_{license_information};"
        db_cursor.execute(sql)
        mydb.commit()
        clean_date_tuple = db_cursor.fetchone()
        clean_date = int(clean_date_tuple[0])

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()

    file_list = glob.glob('/mnt/work/www/upload/images/*.jpg')

    # file_list = glob.glob('/usr/local/nginx/html/upload/images/*.jpg')

    now = datetime.datetime.now()

    for file_path in file_list:
        stat_info = os.stat(file_path)
        mod_time = datetime.datetime.fromtimestamp(stat_info.st_mtime)
        date_diff = now - mod_time

        if date_diff.days > clean_date:
            os.remove(file_path)


def check_update_algorithm():
    license_information = system_setup.main_board_info()

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_check_old = f"SELECT version, algorithm_name FROM video_analysis_user.algorithm_{license_information};"
        db_cursor.execute(sql_check_old)
        old_version_algorithm_tuple = db_cursor.fetchall()

        if old_version_algorithm_tuple is not None:
            for old_version_algorithm in old_version_algorithm_tuple:
                old_version = old_version_algorithm[0]
                algorithm_name = old_version_algorithm[-1]

                sql_check_new = (f"SELECT version FROM video_analysis.algorithm_shop WHERE algorithm_name='%s';"
                                 % algorithm_name)
                db_cursor.execute(sql_check_new)
                new_version = db_cursor.fetchone()[0]

                if old_version != new_version:
                    sql_change_update_available = ((f"UPDATE video_analysis_user.algorithm_{license_information} "
                                                   f"SET update_available='2' WHERE algorithm_name='%s';")
                                                   % algorithm_name)
                    db_cursor.execute(sql_change_update_available)
                    mydb.commit()

                else:
                    continue

    except Exception as e:
        print(e)

    finally:
        db_cursor.close()
        mydb.close()


def update_algorithm():
    jsons = request.json
    license_information = jsons["license_information"]
    algorithm_name = jsons["algorithm_name"]
    latest_version = jsons["version"]

    if len(license_information) > 43:
        license_information = license_information[:43]

    license_information = license_information.replace("-", "_")

    mydb = mysql()
    mydb.connect()
    db_cursor = mydb.cursor()

    try:
        sql_check_model_name = (f"SELECT model_name FROM video_analysis_user.algorithm_{license_information} "
                                f"WHERE algorithm_name='%s';") % algorithm_name
        db_cursor.execute(sql_check_model_name)
        model_name = db_cursor.fetchone()[0]

        sql_check_version = (f"SELECT version, model_name FROM video_analysis_user.algorithm_{license_information} "
                             f"WHERE model_name='%s';") % model_name
        db_cursor.execute(sql_check_version)
        version_tuple_all = db_cursor.fetchall()

        for version_tuple in version_tuple_all:
            version = version_tuple[0]
            model_name = version_tuple[-1]

            model_file_path = r"/mnt/work/www/upload/model/" + model_name
            # model_file_path = r"/usr/local/nginx/html/upload/model/" + model_name
            bak_name = "bak_" + model_name
            # bak_model_file_path = r"/usr/local/nginx/html/upload/model/" + bak_name
            bak_model_file_path = r"/mnt/work/www/upload/model/" + bak_name

            if version == latest_version:
                pass

            else:
                sql_check_model_name = (f"SELECT model_name FROM video_analysis_user.algorithm_{license_information} "
                                        f"WHERE algorithm_name='%s';") % algorithm_name
                db_cursor.execute(sql_check_model_name)
                model_name = db_cursor.fetchone()[0]

                sql_check_docker_args = (f"SELECT docker_uuid, status "
                                         f"FROM video_analysis_user.docker_args_{license_information} "
                                         f"WHERE model_name='%s';") % model_name
                db_cursor.execute(sql_check_docker_args)
                docker_args_tt = db_cursor.fetchall()

                if docker_args_tt != ():
                    for docker_args_t in docker_args_tt:
                        docker_uuid = docker_args_t[0]
                        status = docker_args_t[-1]

                        if status == "Active_M":
                            try:
                                sql_query = (
                                        f"UPDATE video_analysis_user.docker_args_{license_information} "
                                        f"SET status='Inactive_M' "
                                        f"WHERE docker_uuid='%s';"
                                        % docker_uuid
                                )
                                db_cursor.execute(sql_query)
                                mydb.commit()

                                cmd = "nsenter -m -n -t 1 docker kill " + docker_uuid
                                subprocess.Popen(
                                    cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                                )

                            except Exception as e:
                                print(e)

                            finally:
                                db_cursor.close()
                                mydb.close()

                        elif status == "Inactive_M":
                            pass

                        elif status == "Active":
                            try:
                                sql = (
                                        f"UPDATE video_analysis_user.docker_args_{license_information} "
                                        f"SET status='Inactive' "
                                        f"WHERE docker_uuid='%s';"
                                        % docker_uuid
                                )
                                db_cursor.execute(sql)
                                mydb.commit()

                                cmd = "nsenter -m -n -t 1 docker stop " + docker_uuid
                                subprocess.Popen(
                                    cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                                )

                            except Exception as e:
                                print(e)

                            finally:
                                db_cursor.close()
                                mydb.close()

                        elif status == "Inactive":
                            pass

                        else:
                            pass

                else:
                    pass

                try:
                    os.rename(model_file_path, bak_model_file_path)

                except FileNotFoundError as e:
                    print(e)

                    algorithm_name_version = algorithm_name + " --" + latest_version
                    log_action = ("未找到" + "【" + algorithm_name_version + "】"
                                  + "旧版文件，自动下载最新版本--" + latest_version + "。")
                    docker_operation_log(license_information=license_information,
                                         log_type="升级",
                                         device_number="主机",
                                         channel_name="主机",
                                         log_action=log_action,
                                         task_name=algorithm_name_version)

                    sql = ("SELECT model_url, md5 FROM video_analysis.algorithm_shop WHERE algorithm_name='%s';"
                           % algorithm_name)
                    db_cursor.execute(sql)
                    mydb.commit()
                    model_url_tuple = db_cursor.fetchone()
                    model_url = model_url_tuple[0]
                    md5 = model_url_tuple[1]

                    download_result = download_progress(
                        model_url=model_url,
                        model_name=model_name,
                        algorithm_name=algorithm_name,
                        license_information=license_information,
                        version=latest_version
                    )

                    if download_result:
                        sql_update = ((f"UPDATE video_analysis_user_{license_information} "
                                      f"SET version='%s', update_available='%s', md5='%s' WHERE algorithm_name='%s';")
                                      % (latest_version, "1", md5, algorithm_name))
                        db_cursor.execute(sql_update)
                        mydb.commit()

                        return jsonify(
                            code=0,
                            msg="success"
                        )

                sql = ("SELECT model_url, md5 FROM video_analysis.algorithm_shop WHERE algorithm_name='%s';"
                       % algorithm_name)
                db_cursor.execute(sql)
                mydb.commit()
                model_url_tuple = db_cursor.fetchone()
                model_url = model_url_tuple[0]
                md5 = model_url_tuple[1]

                download_result = download_progress(
                    model_url=model_url,
                    model_name=model_name,
                    algorithm_name=algorithm_name,
                    license_information=license_information,
                    version=latest_version
                )

                if download_result:
                    if os.path.isfile(model_file_path):
                        algorithm_name_version = algorithm_name + " --" + latest_version
                        log_action = ("升级" + "【" + algorithm_name + "】" + "算法："
                                      + version + " >>> " + latest_version + " 【成功】" + "。")
                        docker_operation_log(license_information=license_information,
                                             log_type="升级",
                                             device_number="主机",
                                             channel_name="主机",
                                             log_action=log_action,
                                             task_name=algorithm_name_version)

                        sql_update = (f"UPDATE video_analysis_user.algorithm_{license_information} "
                                      f"SET version='%s', update_available='%s', md5='%s' "
                                      f"WHERE algorithm_name='%s';") % (latest_version, '1', md5, algorithm_name)
                        db_cursor.execute(sql_update)
                        mydb.commit()

                        os.remove(bak_model_file_path)

                    else:
                        log_action = ("升级" + "【" + algorithm_name + "】" + "算法："
                                      + version + " >>> " + latest_version + " 【失败】，仍保留旧版--" + version + "。")
                        algorithm_name_version = algorithm_name + " --" + version
                        docker_operation_log(license_information=license_information,
                                             log_type="升级",
                                             device_number="主机",
                                             channel_name="主机",
                                             log_action=log_action,
                                             task_name=algorithm_name_version)
                        os.rename(bak_model_file_path, model_file_path)

                for docker_args_t in docker_args_tt:
                    docker_uuid = docker_args_t[0]
                    status = docker_args_t[-1]

                    if status == "Inactive_M":
                        async def start_docker():
                            try:
                                cmd_1 = "nsenter -m -n -t 1 docker start " + docker_uuid
                                subprocess.Popen(
                                    cmd_1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                                )

                                time.sleep(2)

                            except Exception as e:
                                print(e)

                        async def deliver():
                            try:
                                sql_status = (
                                        f"UPDATE video_analysis_user.docker_args_{license_information} "
                                        f"SET status='Active_M' "
                                        f"WHERE docker_uuid='%s';"
                                        % docker_uuid
                                )
                                db_cursor.execute(sql_status)
                                mydb.commit()

                                sql_task_number = (f"SELECT task_type "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_task_number)
                                mydb.commit()
                                task_number_tuple = db_cursor.fetchone()
                                task_number = str(task_number_tuple[0])

                                sql_docker_port = (f"SELECT docker_port "
                                                   f"FROM video_analysis_user.docker_args_{license_information} "
                                                   f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_docker_port)
                                mydb.commit()
                                docker_port_tuple = db_cursor.fetchone()
                                docker_port = str(docker_port_tuple[0])

                                sql_ip = (f"SELECT ip_addr FROM video_analysis_user.docker_args_{license_information} "
                                          f"WHERE docker_uuid='%s';") % docker_uuid
                                db_cursor.execute(sql_ip)
                                mydb.commit()
                                ip_addr_tuple = db_cursor.fetchone()
                                ip_addr = ip_addr_tuple[0]

                                deliver_args(
                                    jsons=get_db_args(docker_uuid=docker_uuid, license_information=license_information),
                                    suburl=task_classify(type_number=task_number),
                                    port=docker_port,
                                    ip=ip_addr
                                )

                            except Exception as e:
                                print(e)

                        asyncio.run(start_docker())
                        asyncio.run(deliver())

                break

    except Exception as e:
        print(e)

        return jsonify(
            code=1,
            msg="Server Internal Error"
        )

    finally:
        db_cursor.close()
        mydb.close()

    return jsonify(
        code=0,
        msg="success"
    )
